简体   繁体   English

node.js承诺不会在if语句中解析

[英]node.js promise doesn't resolve inside if statement

Looking for some help with promises, why will resolve not work inside this if statement? 寻找承诺的帮助,为什么要解决这个if语句无法正常工作?

async getTrades() {
    return new Promise(function (resolve, reject) {
        if (this.exchange === 'GDAX') {
            resolve('fake')
            console.log('inside GDAX')
        }
    }.bind(this))
}

When I put the resolve outside the if statement (before or after), it works. 当我将解析放在if语句之外(之前或之后)时,它可以工作。 And the console.log('inside GDAX') does fire, so this.exchange ==='GDAX' returns true. 并且console.log('inside GDAX')会触发,因此this.exchange ==='GDAX'返回true。

Here is the function that calls it: 这是调用它的函数:

getHistoricalPortfolioReturn() {
    return new Promise(function (resolve, reject) {
        var exchange_trades_calls = []
        for (var exchange_account in this.exchange_accounts) {
            if (this.exchange_accounts.hasOwnProperty(exchange_account)) {
                exchange_trades_calls.push(this.exchange_accounts[exchange_account].getTrades())
            }
        }
        Promise.all(exchange_trades_calls)
        .then(function (trades) {
            console.log('resolved')
            console.log('trades: ' + trades)
            resolve(trades)
        })
        .catch(function (error) {
            console.error('error: ' + error)
        })
    }.bind(this))
}

You are using an async function. 您正在使用async功能。 You do not have to return a promise as it will be automatically wrapped in a promise. 您不必返回承诺,因为它将自动包装在承诺中。

async getTrades() {
    if(this.exchange === 'GDAX')  return "fake";
}

tldr: You are resolving the incorrect promise. tldr:您正在解决不正确的承诺。

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

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