Home > Back-end >  How do you wait for a return from a function before moving on in node
How do you wait for a return from a function before moving on in node

Time:08-20

I'm new to Node so I'm struggling with this. The script runs as if its "skipping" the bitx.getTicker function inside the while loop. I did some research on asynchronous functions in Node and I just cant seem to get it working on my code. I'm trying to write a crypto-bot with bitx. I tried the .then() method as well and it just keeps on "skipping" the bitx.getTicker function. If I remove the async(from line 1), let tick = await``(from line 5) and the while``` loop it works as intended but just once. I need it to run constantly to check new asking price so once wont work. Thanks in advance.

async function get_ticker(){
  let BitX = require('../lib/BitX')
  while(true){
    let bitx = new BitX(key, secret)
    let tick = await bitx.getTicker(function (err, ticker) {
      // sends ticker object to another function to get values
      get_info(ticker)
    })

    console.log(i)
    i = i   1
  }
}

UPDATE I used a promise and I see it pending but I cant access the ticker variable inside the bitx.getTicker function. How can I access it?

function get_ticker() {
  let BitX = require('../lib/BitX')

  const promise = new Promise((resolve, reject) => {

    let bitx = new BitX(key, secret)
    bitx.getTicker(function (err, ticker) {
      resolve(ticker)
    })

  })
  return promise.resolve
}

var result = get_ticker()
console.log(result)

CodePudding user response:

It seems like your BitX library doesn't have a promise interface but is callback-based, so you need to promisify it:

const { promisify } = require('util')

async function get_ticker(){
  let BitX = require('../lib/BitX')
  while(true){
    let bitx = new BitX(key, secret)
    let tick = await promisify(bitx.getTicker).call(bitx)
    get_info(tick)

    console.log(i)
    i = i   1
  }
}

It would be more performant to create the client only once though:

const { promisify } = require('util')
const BitX = require('../lib/BitX')
const bitx = new BitX(key, secret)
const getBitxTicker = promisify(bitx.getTicker).bind(bitx)

async function get_ticker(){
  while(true){
    const tick = await getBitxTicker()
    get_info(tick)

    console.log(i)
    i = i   1
  }
}

(Note that I used bind instead of call now for binding the bitx instance, because we don't immediately call it now.)

  • Related