Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does await function return pending promise

let request = require('request-promise')

function get(url) {
  let _opt = {}
  let response = (async () => {
    try {
      var ret = await request(url, _opt);
      return ret;
    } catch (e) {
      console.log(e)
    }
  })();
  return response
}

console.log(get('http://www.httpbin.org/ip'))

gives:

Promise { <pending> }

Why doesn't it wait for my response?

like image 232
pguardiario Avatar asked Sep 03 '17 00:09

pguardiario


People also ask

Why is await returning a promise?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Does return await return a promise?

If a promise resolves normally, then await promise returns the result. But in the case of a rejection, it throws the error, just as if there were a throw statement at that line. In real situations, the promise may take some time before it rejects. In that case there will be a delay before await throws an error.

Does async await return a promise?

The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Does await work with promise?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.


1 Answers

Why doesn't it wait for my response?


That's simple, because you are returning a promise. Node js is single thread and is executed in a non blocking way.
That means that return response in your get function is executed before the resolution of response variable.
Try as follow:

let request = require('request-promise')

function get(url) {
    let _opt = {}
    return request(url, _opt);
}

async function some () {
    console.log(await get('http://www.httpbin.org/ip'));
}

some();

This example is also returning a promise, but in this case we are awaiting for the promise resolution.

Hope this help.

like image 107
Hosar Avatar answered Oct 16 '22 04:10

Hosar