确保复合承诺中的异步“.then()"执行 [英] Ensuring asyncronous '.then()' execution in compound promises

查看:34
本文介绍了确保复合承诺中的异步“.then()"执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Typescript 编写 JS 承诺.我有一个复合承诺,即返回承诺的承诺我有:

I am using Typescript to write JS promises. I have a compound promise, i.e. promise which returns a promise I have:

test() {
    addElement("first")
        .then(
            function (val){
                addElement("second");
                console.log("second*);
            })
            .then(
            function (val){
                addElement("third");
                console.log("third*");
            });
}


export function addElement(elementText){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            resolve();
        }, Math.random() * 2000);
    })
    .then(console.log(elementText));
}

我希望这些函数打印出来,first, second*, second,third*,third.但是,我得到:

I would like these functions to print out, first, second*, second, third*, third. However, I get:

JS:首先JS:第二*JS:第三*JS:第三JS:第二个

JS: first JS: second* JS: third* JS: third JS: second

如何在被调用的承诺的 then 完成后让 then 执行?

How do I get the then to execute after the called promises' then has completed?

推荐答案

您不会返回您在 then 块中的承诺.如果你不返回promise,那么then 块会立即return undefined,没有什么会等待它.如果您改为返回承诺,那么承诺链的执行将暂停,直到您返回的承诺得到满足.

You're not returning your promise in the then block. If you don't return the promise, then the then block will return undefined immediately, and nothing will wait for it. If you return a promise instead, then execution of the promise chain will pause until the promise you return has been satisfied.

test() {
    addElement("first")
        .then(
            function (val){
                console.log("second*");
                return addElement("second");
            })
            .then(
            function (val){
                console.log("third*");
                return addElement("third");
            });
}

虽然我个人不认为这是菜鸟错误",但您的描述与诺兰劳森的我们的承诺有问题";继续阅读以获得更深入的解释.

Though I don't personally consider it a "rookie mistake", your description matches "Rookie Mistake #5" in Nolan Lawson's "We have a problem with promises"; read on for a more in-depth explanation.

这篇关于确保复合承诺中的异步“.then()"执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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