7.JavaScript-Promise的并行和串行 - Go语言中文社区

7.JavaScript-Promise的并行和串行


Promise 并行

Promise.all是所有的Promise执行完毕后(reject|resolve)返回一个Promise对象。

最近在开发一个项目中,需要等接口拿到全部数据后刷新页面,取消loding效果

 1  // 项目中请求接口
 2 function getShowProject(resolve, reject) {
 3     $.ajax({
 4       url: `${api}/rrz/member/showProjectById`,
 5       type: 'get',
 6       data: { appId: appId },
 7       success: function (res) {
 8         if (res.result == 'success') {
 9           gather['listBy'] = res.data;
10           resolve();
11         }
12       }
13     });
14   }
15   function getProjectPic(resolve, reject) {
16    ...
17   }
18   function projectRelation(resolve, reject) {
19    ...
20   }
21   function queryProjectDynamicS(resolve, reject) {
22    ...
23   }
24   function showProjectLoveValue(resolve, reject) {
25    ...
26   }
27   function getAppProjectDonorComment(resolve, reject) {
28    ...
29   }
30   // 等待接口全部请求完成后  刷新页面
31   var a1 = new Promise(getShowProject);
32   var a2 = new Promise(getProjectPic);
33   var a3 = new Promise(projectRelation);
34   var a4 = new Promise(queryProjectDynamicS);
35   var a5 = new Promise(showProjectLoveValue);
36   var a6 = new Promise(getAppProjectDonorComment);
37   Promise.all([a1, a2, a2, a3, a4, a5, a6]).then(function () {
38     info = { data: gather }
39     getDetail();
40     console.log('loading效果图消失');
41   })

 

Promise 串行

在项目的实际操作中会用到串行调用方法的情况,实现异步执行,例如
有三个方法,方法一、方法二、方法三,需要执行完方法一之后执行方法二,执行完方法二之后执行方法三,可以用Promise实现,简单的模拟做法如下:

function one(){
    console.log(11111);
}

function two(){
    console.log(22222);
}

function three(){
    console.log(33333);
}
function fiveP(func){
    return new Promise(function(resolve, reject) {
        func();
        resolve();
    });
}

p.then(fiveP(one))
.then(fiveP(three))
.then(fiveP(two))
.then(function(result) {
    console.log('最后执行' + result);
});
// 执行结果 
// 1111
// 3333
// 2222
// 最后执行

 

版权声明:本文来源博客园,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.cnblogs.com/xiaole9924/p/11842180.html
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2019-11-17 12:36:48
  • 阅读 ( 1283 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢