简体   繁体   English

节点链接承诺不返回已解析的值

[英]node chaining promise doesn't return resolved value

I am trying to chain a promise which will take an input, append to the input, pass back the result before finally resolving the Promise. 我试图链接一个承诺,该承诺将接受输入,追加到输入,在最终解决Promise之前传递结果。 Code executes and I had added some console.log so I know that the value of _add24h is getting appended but it seems the .then does not pass to the main Promise as it finally resolves to the initial value. 代码执行后,我添加了一些console.log,所以我知道_add24h的值将被追加,但是.then并没有传递给主要Promise,因为它最终解析为初始值。

My Promise.all elsewhere in the code is getting values passed but does not contain the data from the .then 我的Promise.all在代码的其他地方正在传递值,但不包含来自.then的数据

promise2 = new Promise((resolve,reject) => {
    binance.prevDay(coin + `BTC`, (error, prevDay, symbol) => {
        for (var obj in prevDay) {
            if (obj.includes("priceChange")) {
                _add24h["24h Change"] = `\u0E3F` + prevDay[obj];
            }
        }
        resolve(_add24h);
    })
    }).then(function(_add24h) {
        return new Promise ((resolve,reject) => {
            binance.prevDay(coin + `USDT`, (error, prevDay, symbol) => {
                for (var obj in prevDay) {
                    if (obj.includes("priceChange")) {
                         _add24h["24h Change"] = _add24h["24h Change"] + "\n$" + parseFloat(prevDay[obj]).toFixed(2);
                    }
                }
            })
        })
        resolve(_add24h);
    })

Promise.all([promise1,promise2]).then(function(_addFields) {
    Object.keys(_addFields).forEach(function(prop) {
        Object.keys(_addFields[prop]).forEach(function(key) {
            embed.addField(key,_addFields[prop][key],true)
        });
    });
    message.channel.send({embed});
});

If you are resolving secon promise outside of your callback so it is actually getting resolved even before binance.prevDay(coin + 'USDT',...) run. 如果您要在回调之外解决seco​​n promise,那么即使在binance.prevDay(coin + 'USDT',...)运行之前,它实际上也已得到解决。

So you need to change your call as follow and enclose resolve in callback 因此,您需要按照以下方式更改呼叫并将解析包含在回调中

promise2 = new Promise((resolve,reject) => {
    binance.prevDay(coin + `BTC`, (error, prevDay, symbol) => {
        for (var obj in prevDay) {
            if (obj.includes("priceChange")) {
                _add24h["24h Change"] = `\u0E3F` + prevDay[obj];
            }
        }
        resolve(_add24h);
    })
})
.then(function(_add24h) {
    return new Promise ((resolve,reject) => {
        binance.prevDay(coin + `USDT`, (error, prevDay, symbol) => {
            for (var obj in prevDay) {
                if (obj.includes("priceChange")) {
                     _add24h["24h Change"] = _add24h["24h Change"] + "\n$" + parseFloat(prevDay[obj]).toFixed(2);
                }
            }
            resolve(_add24h);
        })
    })
 })

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

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