简体   繁体   English

节点承诺链解析不等待.then

[英]node Promise chain resolution not waiting for .then

I have this particular Promise chain with the promise and 1 then. 我有这个带有Promise和1的Promise链。 I want the first Promise to run and populate an object with keyed values. 我希望第一个Promise运行并使用键值填充对象。 This works fine. 这很好。

I then want a .then function to execute which will concat some values to the original object. 然后,我希望执行一个.then函数,该函数会将一些值连接到原始对象。 Again this is working fine. 再次,这很好。

My problem is the resolve is occurring before the .then completes which is not what I want. 我的问题是解决方法是在.then完成之前发生的,这不是我想要的。 I understood .then would execute and finally return result before the resolve settles. 我知道.then将执行并最终在解决方案解决之前返回结果。 If I simplify the code to just simply concat the value it works. 如果我简化代码,只是简单地合并它的值即可。 I believe my problem is the first operation in the .then is itself an async object. 我相信我的问题是.the中的第一个操作,然后它本身是一个异步对象。 I am not sure how to make the .then wait for binance.prevDay to complete before returning result. 我不确定如何使.then等待binance.prevDay完成,然后返回结果。

The console.log output looks like this: console.log输出看起来像这样:

Resolving
Resolved
฿0.00153400
entered
Exit฿0.00153400
$14

All values are what I want, but I want the Resolved to be at the end. 所有值都是我想要的,但我希望“解决”在最后。

promise2 = new Promise((resolve, reject) => {
        binance.prevDay(coin + `BTC`, (error, prevDay, symbol) => {
            for (var obj in prevDay) {
                if (obj.includes("priceChangePercent")) {
                    _add24h["24h Percent"] = new Number(parseFloat(prevDay[obj]).toFixed(2)) + `%`;
                } else
                if (obj.includes("priceChange")) {
                    _add24h["24h Change"] = `\u0E3F` + prevDay[obj]; // + `\n\$` + parseFloat(prevDay[obj]*_btcusdt).toFixed(2);
                } else
                if (obj.includes("highPrice")) {
                    _add24h["24h High"] = `\u0E3F` + prevDay[obj];
                } else
                if (obj.includes("lowPrice")) {
                    _add24h["24h Low"] = `\u0E3F` + prevDay[obj];
                }
            }
            console.log("Resolving")
            resolve(_add24h);
            console.log("Resolved")
        })
    })
    .then(function (result) {
        binance.prevDay(coin + `USDT`, (error, prevDay, symbol) => {
            for (var obj in prevDay) {
                //console.log(prevDay[obj]);
                if (obj.includes("priceChangePercent")) {
                    _add24h["24h Percent"] = prevDay[obj];
                } else
                if (obj.includes("priceChange")) {
                    console.log("entered")
                    _add24h["24h Change"] = _add24h["24h Change"] + "\n$" + new Number(parseFloat(prevDay[obj]).toFixed(2));
                    console.log("Exit" + _add24h["24h Change"])
                }
            }
        })
        console.log(_add24h["24h Change"])
        return result;
    })

From what I understand, that is the expected order of execution. 据我了解,这是预期的执行顺序。

Calling resolve() inside your first promise does not necessarily execute the then handler immediately (ie, calling resolve does not add the then handler to the call stack).. It will be queued for execution and the call to resolve returns, and the console.log("Resolved") in the promise handler. 在您的第一个promise中调用resolve()并不一定立即执行then处理程序(即,调用resolve不会将then处理程序添加到调用堆栈中)。它将排队等待执行,并且要resolve的调用返回,并且console.log("Resolved")在承诺处理程序中。 The then method is executed later on the 'next tick' assuming nothing else has been queued up. 假设没有其他排队,则稍后在“下一个滴答”上执行then方法。

However, this is just my superficial understanding and it may depend on the implementation of Promises used. 但是,这只是我的肤浅理解,可能取决于所使用的Promises的实现。

Calling .resolve() or .reject() is an asynchronous action, and is just a signal to the associated handler that the promise has been fulfilled or rejected. 调用.resolve()或.reject()是一个异步操作,并且仅是向关联的处理程序发出的信号,即诺言已经实现或被拒绝。 It doesn't necessarily mean that the next lines will be executed only after the then part has completed execution. 这并不一定意味着仅在then部分完成执行之后才执行下一行。

Please read the official javascript documentation on promises to have a better understanding: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 请阅读有关承诺的javascript官方文档,以更好地了解以下内容: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

In order to have "Resolved" at the end, you should put it at the end of your then() chain. 为了使“ Resolved”位于末尾,应将其放在then()链的末尾。

The important point here is: resolve resolves a promise and not a promise chain. 这里的重点是: resolve解决承诺而不是承诺链。
You have two promises in your code: 您的代码中有两个承诺:
The one you create with new Promise and the one you create with .then . new Promise创建的一个和用.then创建的一个。
As expected, the call to resolve resolves the first promise. 正如预期的那样, resolve的电话解决了第一个诺言。 This is the prerequisite for the second promise to run. 这是第二个承诺得以履行的前提。 If you wouldn't call resolve on the first promise, the .then promise would never run. 如果您不对第一个诺言调用resolve ,那么.then诺言将永远不会运行。

If you want code to run after your .then , append that code with another .then . 如果您希望代码在.then之后运行,请将该代码附加另一个.then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM