简体   繁体   中英

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. 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.

My Promise.all elsewhere in the code is getting values passed but does not contain the data from the .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.

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);
        })
    })
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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