用Promise处理异步函数

处理函数之间的异步问题,使其同步进行的其中一种方法,就是使用Promise。Promise在ES6中被提出。

使用示例如下:

假如有三个函数,要求按getone、gettwo、getthree的顺序执行。函数参数为Promise特有的resolve和reject,reslove和reject可在函数中返回结果。

 1 //异步方法一
 2  function getone(resolve,reject){
 3     setTimeout(function(){
 4         resolve("1");
 5     },3000)
 6 }
 7 //异步方法二
 8   function gettwo(resolve,reject){
 9       setTimeout(function(){
10           resolve("2");
11     },3000)
12 }
13 //异步方法三
14  function getthree(resolve,reject){
15      setTimeout(function(){
16          resolve("3");
17       },3000)
18  }

 

将getone函数作为参数生成Promise对象,用then来串联,result能拿到上一个函数返回的结果,then里面返回的是一个新的Promise对象,从而实现串联。

 1 var result = new Promise(getone)
 2 .then(function(resultone){
 3     console.log('----------one------------');
 4     console.log(resultone);
 5     return new Promise(gettwo);
 6 })
 7 .then(function(resulttwo){
 8     console.log('----------two------------');
 9     console.log(resulttwo);
10     return new Promise(getthree);
11 })
12 .then(function(resultthree){
13     console.log('-----------three---------');
14     console.log(resultthree);
15 })
16 .catch(function(err){
17     console.log(err);
18 })

 

结果如下:

 

 从而实现了这三个函数间的同步执行和前后传参。

 

转载于:https://www.cnblogs.com/luoyihao/p/11592474.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值