Why does the wait function wait?

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 is he not waiting for my answer?

+4
source share
2 answers

Why is he not waiting for my answer?


It is simply because you are returning a promise. Node js is the only thread and is executed in a non-blocking way.
This means that the return response in your get function is executed before the response variable is resolved.
Try the following:

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 also returns a promise, but in this case, we expect to resolve the promise.

I hope for this help.

+3
source

Async , . , , , .

, , . await . , get, :

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

UPDATE:

(, ).

response , async. , ret , , ret. response , . , , -, , , try :

try {
    return request(url, _opt)
}

request , , .

response , response, get . (, , ). await .then get, .

: https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8 "Pitfall 1: not waiting"

+2

Source: https://habr.com/ru/post/1684965/


All Articles