Search code examples
node.jsapipromisecryptocurrency

Why console.log is executing before promise is fulfilled in node.js


I'm trying to pull data from an external API, then create an array of bitcoin bid prices, then console log the output. The problem is that the console log function is executing before the data is returned from the server. This creates an empty array. Please advise on how I can fix this.

const express = require('express')
const app = express()
const port = 6800
app.listen(port, () => {
    port
})
const GateApi = require('gate-api');
const client = new GateApi.ApiClient();

var _array = [] // store data returned from server

const api = new GateApi.SpotApi(client);  //gate-io api  
const currencyPair = "BTC_USDT"; // string | Currency pair
const opts = {
    'limit': 10 // limit records returned
};

api.listOrderBook(currencyPair, opts).then(value => {
    return value.body.bids.forEach(function(data) {
        _array.push(data);
    });
}, error => console.error(error)).then(console.log(_array))


Solution

  • The argument to then should be a function. That function will get executed once the promise fulfills.

    You are not passing a function, you are passing the result of console.log().

    Instead of:

    .then(console.log(foo))
    

    You'll want:

    .then(() => console.log(foo))