美文网首页
Promise 实现方法(请求)的异步(串行)执行

Promise 实现方法(请求)的异步(串行)执行

作者: Small_Song | 来源:发表于2021-05-22 13:19 被阅读0次

在项目的实际操作中会用到串行调用方法的情况,实现异步执行,例如
有三个方法,方法一、方法二、方法三,需要执行完方法一之后执行方法二,执行完方法二之后执行方法三,这样的串行的执行顺序可以用层层嵌套的方法来实现,但是这样的话方法嵌套的深看起来就很麻烦,可以用Promise实现,简单的模拟做法如下:

function fourO() {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            console.log(44444);
            resolve();
        }, 1500);
    });
}

function threeO(){
    return new Promise(function(resolve, reject) {
        console.log(333);
        resolve(123);
    });
}

function twoO(){
    return new Promise(function(resolve, reject) {
        console.log(222);
        resolve();
    });
}

function oneO(){
    return new Promise(function(resolve, reject) {
        console.log(111);
        resolve();
    });
}
var p = new Promise(function(resolve, reject) {
    resolve();
});

p.then(oneO)
.then(fourO)
.then(twoO)
.then(threeO)
.then(function(result) {
    console.log('Got value: 最后执行' + result);
});

执行结果如下:

11111
44444
22222
33333
Got value: 最后执行123

用方法fourO模拟接口的调用返回的时间差,这样可以控制实际运用中方法的调用的顺序。

另一种合成用一个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('Got value: 最后执行' + result);
});

执行结果为:

11111
33333
22222
Got value: 最后执行

记录一下,方便使用。

相关文章

网友评论

      本文标题:Promise 实现方法(请求)的异步(串行)执行

      本文链接:https://www.haomeiwen.com/subject/akinjltx.html