smart_beaver
smart_beaver

Reputation: 87

Node async function returns undefined

var https = require('https');
async function getOrderBook(){
  var options = {
    host: 'api.bybit.com',
    port: 443,
    path: '/v2/public/orderBook/L2?symbol=BTCUSD',
    method: 'GET'
  };

  https.request(options, function(res) {
    res.on('data', function (chunk) {
      //console.log(chunk);
      return chunk;
    });
  }).end();
}

console.log(getOrderBook())

The following logs

Promise { undefined }

in the console. However, I can log it fine from inside the function. How to make it so it waits for the function to resolve?

Upvotes: 0

Views: 85

Answers (2)

Mark
Mark

Reputation: 92440

https.request() takes a callback function. That's the function you pass in the second argument. When you return inside the function you are returning to the caller of that function, not getOrderBook(). Since there are no promises anywhere async/await is not really useful. You could wrap the request in a promise and return that, or you can pass a callback to getOrderBook() and when the request is finished call it with the data. For example:

var https = require('https');

function getOrderBook(cb) {
  var options = {
    host: 'api.bybit.com',
    port: 443,
    path: '/v2/public/orderBook/L2?symbol=BTCUSD',
    method: 'GET'
  };


  https.request(options, function(res) {
    let data = ''
    res.on('data', function(chunk) {
      data += chunk;
    });
    res.on('end', function() {
      // All done, call the callback
      cb(JSON.parse(data))
    })
  }).end();
}

// pass a callback that tells it what to do with the data
getOrderBook((data) => console.log(data.result))

Alternatively you can use a library like axios that has native promise support.

Upvotes: 1

Mike Gerard
Mike Gerard

Reputation: 169

You can put await before you call the async function, but beware you need to be in an async function to use await

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Op%C3%A9rateurs/await

Upvotes: 0

Related Questions