首页 > promise的用法

promise的用法

疑惑1:

程序大部分的调用链是这样的:

promise.then(A).then(B).then(C).then(D)

但是B满足某种条件,需要这样调用:

promise.then(A).then(B).then(C1).then(C2).then(D)

这种情况该怎么做?


新的说明:

这个条件并不是在外围可以确定的

例如:


// 并不可以这么做。state必须在B函数执行完之后才能确定
if(state){
  promise.then(A).then(B).then(C1).then(C2).then(D)
}else{
  promise.then(A).then(B).then(C).then(D)
}

疑惑2:

如何在循环中使用promise?


推荐es7的async/await
用同步方式写异步代码


疑惑1

修正:

promise
    .then(A)
    .then(B)
    .then(function(state){
        if(state){
            return C1.then(C2);
        }
        return C;
    })
    .then(D);

好像也不算帅,期待更屌的实现

疑惑2

如果发生在循环里,譬如:对一个数组进行遍历,对每一元素处理的结果都是一个Promise,可以这样写:

var userIds = ['aaa', 'bbb', 'ccc'];

//这里getUserById返回的是Promise
var promises = arr.map(userIds => getUserById(userId));

Promise
    .all(promises)
    .then(function(users) {
        console.log(users); //这里就是users的列表了
    });

疑问1可以这样

promise.then(A).then(B).then(function () {
    if (state) {//state可以来自B或A
        return C();
    } else {
        return C1().then(C2);
    }
}).then(D);

疑问2,如果循环需要并行用Promise.all

let functions = [...]
let promises = function.map((fn) => fn());
Promise.all(promises).then((results) => console.log(results))

如果要串行就这样

let functions = [...]
let promise = funcitons.reduce(function (now, fn) {
    reutrn now.then(fn);
}, Promise.resolve());
promise.then((result) => console.log(result));
【热门文章】
【热门文章】