欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

promise() 用法

程序员文章站 2022-07-02 22:54:20
...
es6 promise() 用法
Promise 是异步操作,用于解决回调函数和事件
模拟promise环境
<!DOCTYPE html>
<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>Document</title>
</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>
拿着 不谢 请叫我“锤” 谢谢!!!
相关标签: promise() 用法