首页 > 技术文章 > 用Promise处理异步函数

luoyihao 2019-09-26 16:14 原文

处理函数之间的异步问题,使其同步进行的其中一种方法,就是使用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 })

 

结果如下:

 

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

 

推荐阅读