1

This code returns a promise which is pending I want to store the returned data from insta function into data array.

cs2.js:- 
    async function insta(mode, coin) {
      coin = coin.toLowerCase();
      var price;
      var quantity;
      await new Promise(function (resolve, reject) {
        request.get(url, function (err, response, body) {                 //requests to api
          a = (JSON.parse(body))['rates'];                                //converts body to JSON
      for (i = 0; i < a.length; i++) {
        if (a[i].coin == coin) {
          price = parseFloat(price = a[i].rate).toFixed(2);           // assigns price
        }
      }
      quantity = (JSON.parse((JSON.parse(body))['volume']['value'])['INR'][coin.toUpperCase()]).toFixed(3);  //assigns qunatiity
      resolve();
    });
  });
  return [price, quantity, "Insta"];

}

function p2pSignal(coin, mode, noOfP2p, p2pList, message) {
  data = [];
  data.push(insta(mode, coin));                               // I want to store the data in data array
  console.log(data);
  //setTimeout(function(){console.log(data);},3000)
}

p2pSignal("XRP", "SELL", 4, 'INSTA', "1"); // CALLING THE FUNCTION

Command Line Code:-

node cs2.js
[ Promise { <pending> } ]
Smitk
  • 91
  • 1
  • 7
  • await on `request.get` – Jojo Narte Aug 02 '18 at 16:50
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Aug 02 '18 at 16:50
  • 1
    Avoid doing too much stuff inside the `new Promise` constructor. You should only call `resolve(body)`, then write `const body = await new Promise(…);` and do the rest outside. – Bergi Aug 02 '18 at 17:46

1 Answers1

1

A function that uses async function should implement promise control flow, e.g. be async too:

async function p2pSignal(coin, mode, noOfP2p, p2pList, message) {
  data = [];
  data.push(await insta(mode, coin));
  console.log(data);
}
Estus Flask
  • 206,104
  • 70
  • 425
  • 565