7. JavaScript-Promise parallel and serial

Parallel Promise

Promise.all is finished after all Promise (reject | resolve) returns a Promise object.

In a recent development project, and other interfaces need to get the data to refresh the entire page, cancel loding effect

 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   functiongetProjectPic (Resolve, Reject) {
 16     ...
 . 17    }
 18 is    function projectRelation (Resolve, Reject) {
 . 19     ...
 20 is    }
 21 is    function queryProjectDynamicS (Resolve, Reject) {
 22 is     ...
 23 is    }
 24    function showProjectLoveValue (Resolve, Reject ) {
 25     ...
 26 is    }
 27    function getAppProjectDonorComment (Resolve, Reject) {
 28     ...
 29    }
 30    // wait for the completion of the request to refresh all the interface page 
31 is    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      the console.log ( 'FIG loading effect disappears' );
 41    })

 

Promise Serial

In the actual operation of the project will be used in case of calling a method of serial asynchronous execution, for example,
there are three methods, a method, Method Two, Three methods need to perform a complete method after the execution method two, two executed after executing the method three methods can be implemented Promise, simple simulation approach is as follows:

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);
}); 
// execution result 
@ 1111 
@ 3333 
@ 2222 
@ final performance

 

Guess you like

Origin www.cnblogs.com/xiaole9924/p/11842180.html