Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js promise doesn't resolve inside if statement

Looking for some help with promises, why will resolve not work inside this if statement?

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. And the console.log('inside GDAX') does fire, so this.exchange ==='GDAX' returns 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))
}
like image 640
JBaczuk Avatar asked Mar 13 '26 18:03

JBaczuk


1 Answers

You are using an async function. 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.

like image 148
Derek 朕會功夫 Avatar answered Mar 16 '26 07:03

Derek 朕會功夫



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!