0

I am trying to use async/ await in request module but I cannot get it to run. I need the response function to wait for the request to complete ( the request pulls from data in a search-bar in browser) I have tried using x = await res, which looks like its not allowed, I have also tried let x = await getStockX() to no avail. I understand the need for await so I no longer run into undefined, but have struggled to find it used in this particular setup.


function getStockX(getUrl){
    return new Promise(async(resolve, reject) => {
    request({
        url: 'https://stockx.com/api/products/' + getUrl + '?includes=market&currency=USD',
        method: "GET", 
        headers: stockxGETHeaders
      },
    async function(err, res, body){
    let x = await getStockX(); // does not work
    let x = await res; // does not work
    let json = JSON.parse(body)

    console.log(json)

    resolve(sku)

        }); 
    })
}
N3VO
  • 39
  • 6
  • async/await is just syntactic sugar for Promise. request is a callback base library, therefore, async/await does not work on it. – AngelSalazar Apr 13 '20 at 21:42
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Apr 13 '20 at 21:47
  • In your specific case, you want to just use the `request-promise` package instead. – Bergi Apr 13 '20 at 21:48
  • @Bergi thank you or clarifying, my problem then is why is it not waiting for the response to finish with resolve? – N3VO Apr 13 '20 at 22:12
  • Awaiting `getStockX()` in there makes no sense as it would be a recursive call. `await res` does not make sense as `res` is not a promise. Did you try `console.log(err, res, body)`? – Bergi Apr 14 '20 at 12:26
  • Btw it really should be `async function getStockX() { const res = await requestPromise({url: …}); const sku = JSON.parse(res.body); return sku; }` – Bergi Apr 14 '20 at 12:27

0 Answers0