嵌套的Promise执行不同步 [英] Nested Promise execution is out of sync

查看:54
本文介绍了嵌套的Promise执行不同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的设置,如此小提琴所示:

I have a simple setup, illustrated in this fiddle:

var doDelay = function(who) {
    return Promise.delay(50)
        .tap(function() {
            console.log(who + ' done');
        });
};

Promise.resolve()
    .then(doDelay('a'))
    .tap(function() {
        console.log('a done2');
    })
    .then(doDelay('b'))
    .tap(function() {
        console.log('b done2');
    })
    .then(function() {
        console.log('all done!');
    });

输出为:

a done2
b done2
all done!
a done
b done

但是我希望:

a done
b done
a done2
b done2
all done!

我在做什么错了?

推荐答案

正如Bergi指出的那样,将诺言作为then的参数传递是无效的,但是即使被允许,另一个问题是尽快当您调用delayMany('a')时,其中的Promise.delay(50)将开始执行,这不是您要执行的操作.

As Bergi points out, it's not valid to pass a promise as the argument to then, but even if it were allowed, another issue is that as soon as you call delayMany('a'), the Promise.delay(50) inside it will start executing which is not what you are looking to do.

您可以将调用包装在匿名函数中,也可以使用.bind():

You can either wrap the call in an anonymous function, or use .bind():

var delayMany = function(who) {
    return Promise.delay(50)
    .tap(function() {
        console.log(who  + ' done');
    });
};

Promise.resolve()
.then(delayMany.bind(null, 'a'))
.tap(function() { console.log('a done2'); })

.then(delayMany.bind(null, 'b'))
.tap(function() { console.log('b done2'); })

.then(function() {
    console.log('all done!');
});

Q:为什么then在向其传递承诺时不抛出错误?"

Q: "Why doesn't then throw an error when I pass a promise to it?"

对此的答案在承诺/A +规范中:

promise的then方法接受两个参数:

promise.then(onFulfilled, onRejected)

2.2.1. onFulfilledonRejected都是可选参数:

2.2.1. Both onFulfilled and onRejected are optional arguments:

2.2.1.1. 如果onFulfilled不是函数,则必须将其忽略.

2.2.1.1. If onFulfilled is not a function, it must be ignored.

这篇关于嵌套的Promise执行不同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆