console.log not logging with await variable

Viewed 1727

I am trying to log the data of a promise to my console but it's not showing. i have tried defining then in then and on top of functions and tried with let and redefining the before executing the algorithm but. no response

sample

var trade;
const getTrades = async () => {
    return await axios({
        method: 'get',
        url: bUrl + tradeQuery
    })

}


const getSOrders = async () => {
    return await axios({
        method: 'get',
        url: bUrl + mOrderQuery
    })

}
const postOrder = async() => {
  const binanceRest = new api.BinanceRest({
      ...
    }
  )

  binanceRest.newOrder({
      ...
    })
    .then(async(data) => {
      const trades = await getTrades()
      const mOrders = await getSOrders()
      console.log(data)
      console.log(trades)
    })
    .catch((err) => {
      console.error(err)
    })
}

(
    postOrder(),
    async () => {
        const trades = await getTrades()
        const mOrders = await getSOrders()
        const sells = mOrders.data.asks
        const buys = mOrders.data.bids

        while (true/*while order is in */) {

            trade = trades.data[trades.data.length - 1]
             console.log(sells)
           
        }
    }


)()

4 Answers

Your code is stuck in a an infinite while loop. Since node is single threaded, it will continue to execute the loop until broken and never execute the .then code in the original promise. You should be able to easily see this by commenting out the while loop.

Specifically: binanceRest.newOrder is async call. It's true that postOrder is called first, but depending on the how nodejs decides to optimize, all of the awaits are hit at the same time. When the awaits resolve, if Nodejs decides that postOrders will resume your console.log will write, however if the while loop it hit first, then your program will be stuck there.

I'm sorry to say this, but I can see a lot of confusing things in this code.

while(true) {
  trade = trades.data[trades.data.length - 1];
  console.log(sells);
}

this will never exits. If you omitted part of your code is not a good idea as this makes us harder to give you the actual answer to your question. If this is your real code, I would change in

while(trades.data.length) {
  trade = trades.data.pop();
  console.log(sells);
}

postOrder is an async function which deals with Promise, and this is confusing: I would rewrite it as

const postOrder = async() => {
  try {
    const binanceRest = new api.BinanceRest({ ... });

    const data = await binanceRest.newOrder({ ... });
    const trades = await getTrades()
    const mOrders = await getSOrders()
    console.log(data)
    console.log(trades)
  }
  catch(err) {
    console.error(err)
  }
}

Last postOrder is an async function which is called without await and this is source of confusion as well.

I would start cleaning your code, probably many problem will be solved as well.

Hope this helps.

Is not an "await" problem

I've added a bunch of console.log instructions at your code and there's no problem printing anything. Try adding the same to your original code, assuming your API's are working fine there's no reason for failure.

The following snippet mocks your API's, please take a look at the result. Your error must be at your logic, api's or syntax.

Also add a safe break inside your while, something like this: if (calls++ > 5) { break; }, to me it seems that the infinite loop is the problem.

/* MOCK API'S */
let test = 0, calls = 0;
const fakePromise = (arg, apiName) => { return { then: (f1, f2) => { console.log('mocked result for ' + apiName); return f1(arg); } }; };
const axios = (args) => { console.log('-> axios is called', args); return fakePromise({data: { asks: ['ask'], bids: ['bid'], length: 1, 0: 'fake index'} }, args.url); };
const api = { BinanceRest: function(){ return { newOrder: () => fakePromise(' -> newOrder result <- ', 'newOrder')}; } };
const bUrl = 'bUrl/', mOrderQuery = 'mOrderQuery', tradeQuery = 'tradeQuery';


/* YOUR CODE STARTS HERE */
var trade;
const getTrades = async () => {
    console.log('-> getTrades is called');
    return await axios({
        method: 'get',
        url: bUrl + tradeQuery
    });
}

const getSOrders = async () => {
    console.log('-> getSOrders is called');
    return await axios({
        method: 'get',
        url: bUrl + mOrderQuery
    })

}

const postOrder = async() => {
  console.log('step 1');
  const binanceRest = new api.BinanceRest({
//      ...
  });

  console.log('step 2');
  binanceRest.newOrder({
//      ...
  })
    .then(async(data) => {
      console.log('step 3');
      const trades = await getTrades()
      const mOrders = await getSOrders()
      console.log('step 4.2');
      console.log('data: ', data)
      console.log('trades: ', trades)
      console.log('mOrders', mOrders)
    })
    .catch((err) => {
      console.error(err)
    })
}

// test
(
    postOrder(),
    async () => {
        console.log('step 4.1');
        const trades = await getTrades()
        const mOrders = await getSOrders()
        console.log('step 5', mOrders);
        const sells = mOrders.data.asks
        const buys = mOrders.data.bids
        console.log('step 5.0');

        while (true/*while order is in */) {

            console.log('step 5.' + (test++));
            trade = trades.data[trades.data.length - 1]
            console.log('sells: ', sells)
            if (calls++ > 5) {
              console.log('way too much calls, break! ');
              break;
            }
        }
    }
)()

Take a closer look at your postOrder func:

const postOrder = async() => {
  const binanceRest = new api.BinanceRest({ ... })

  binanceRest.newOrder({ ... })
    .then(...)
    .catch(...)
}

Now imagine the scenario when a typo has been made, f.e. it should be new api.FinanceRest(...) and as a result you end up with error:

Uncaught (in promise) TypeError: api.BinanceRest is not a function

Rest of code in postOrder is simply skipped, no console.logs. So the main point here: if in new api.BinanceRest({ ... }) something leads to an error (any error) than you'll end up with situation you have right now.

And also worth to mention that an async anonymous function with while loop still gets executed and that's because postOrder is an async func which means it returns a pending Promise.

Try running this in you browsers console to get more sense of what's goin' on:

function delay(sec) {
  return new Promise((res, rej) => {
    setTimeout(() => res("delay " + sec + "sec"), sec * 1000);
  });
}

async function getTrades() {
  return await delay(0.1);
};

async function getSOrders () {
  return await delay(0.2);
};

async function postOrder() {
  console.log("postOrder");

  const api = {};
  const binanceRest = api.BinanceRest()

  delay(0.4)
    .then(async (data) => {
      console.log("postOrder result")
      const trades = await getTrades()
      const mOrders = await getSOrders()
      console.log(trades)
      console.log(mOrders)
    })
    .catch(err => {
      console.error(err);
    });
};

(postOrder(),
async () => {
  const trades = await getTrades();
  const mOrders = await getSOrders();
  console.log("gfdfg");
})();

Related