promise() 用法

没有特别的幸运,那么就特别的努力!!!

异步处理:

方法一:在没有出现promise之前,处理异步——延时加载,setTimeout()

	function f1(callback){
        setTimeout(()=>{
            var res = 'f1'
            console.log('我先执行从后台获取到了f1');
            callback(res)
        },1000)
    }
    function f2(value){
        console.log(value);
    }

    f1(f2)      

promise() 用法_第1张图片
方法二:promise

// promise新建后会立即执行
    console.log('hi');
    
    const promise = new Promise(function(resolve,reject){
        console.log('promise');
        resolve()
    })

    promise.then(function(){
        console.log('resolve');
    })

    console.log('hello');

promise() 用法_第2张图片

es6 promise() 用法

Promise 是异步操作,用于解决回调函数和事件
模拟promise环境

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Documenttitle>
head>
<body>
  
  <script>
    let status =  1;
	//账号登录
    let userLogin = (resolve,reject) => {
    	setTimeout(() => {
    		if(status == 1){
    			resolve({data:"登陆成功",msg:"xxxx",token:"afsafsd111"});
    		}else{
    			reject("失败");
    		}
    	},2000);
    };
	//登录成功  获取用户信息
    let getUserInfo = (resolve,reject) => {
    	setTimeout(() => {
    		if(status == 1){
    			resolve({data:"获取用户信息成功",msg:"adsasfsd",token:"afsafsd222"});
    		}else{
    			reject("失败");
    		}
    	},1000);
    }
	//.then回调
    new Promise(userLogin).then(res => {
    	console.log('用户登录成功')
    	console.log(res)
    	return new Promise(getUserInfo)
    }).then(res => {
    	console.log("获取用户信息成功");
    	console.log(res)
    })
  script>
body>
html>
拿着 不谢 请叫我“锤” 谢谢!!!

你可能感兴趣的:(Es6)