admin 管理员组

文章数量: 1086019

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)
           
        }
    }


)()

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)
           
        }
    }


)()

Share Improve this question edited Jul 5, 2020 at 15:32 Diako Sharifi 4634 silver badges16 bronze badges asked Jun 30, 2020 at 22:17 Camille BasbousCamille Basbous 3976 gold badges14 silver badges39 bronze badges 7
  • 2 So to get the dumb question out of the way. Are you ever calling postOrder? – Taplar Commented Jun 30, 2020 at 22:21
  • Are you sure that binanceRest.newOrder is actually resolving the promise? Try console logging the promise object itself to see if it ever fills. – Splox Commented Jun 30, 2020 at 22:29
  • @Splox yes it is, the order is taking place, the issue is that everything in .then can be logged if const trades = await getTrades() const mOrders = await getSOrders() are not defined – Camille Basbous Commented Jun 30, 2020 at 23:19
  • I edited the question, by the way the console.log in the while works – Camille Basbous Commented Jun 30, 2020 at 23:24
  • 1 Please @CamilleBasbous, try to fix the issues I wrote in my answer and you'll see a lot of problems will solve. – Daniele Ricci Commented Jul 7, 2020 at 14:51
 |  Show 2 more ments

4 Answers 4

Reset to default 4 +50

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 menting 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");
})();

本文标签: javascriptconsolelog not logging with await variableStack Overflow