D
D
Denis Shcherbina2020-06-24 00:35:23
Node.js
Denis Shcherbina, 2020-06-24 00:35:23

Why await doesn't work in my case?

You need to make node.js code work consistently. There is a function that works late, you need to wait for its execution. Now it returns a huge pile of json code, with no response. I see the answer in the console later, when all the subsequent code of the main function has completed. Why await doesn't work? What am I doing wrong?

async function вызываемая_функция(){
  return await request.get({url:'https://test_site/'}, function optionalCallback(err, body) {
    data = JSON.parse(body);
    console.log(data); // "Успех!" - выводит отлично, но слишком поздно
    return data ; // "Успех!";
  });
}

async function основная_функция(callback){
  ...
  let get_data = await вызываемая_функция();
  console.log(get_data); // Вместо слова "Успех!" выводит много ненужного кода
  ...
  return callback(...);
}


If I wrap the code of the called function in return await Promise.all(...), I get the following error:
TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

How can I wait for the function to execute and get a response? Without callback nesting, but in the get_data variable, as in my example...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Polos, 2020-06-24
@Denis_maker

You take request.get({}, callback) in the first function, work in "callback style", and expect await to wait and unpack the asynchronous action on the right, this is a mistake. Wrap request.get in a Promise and work with async await.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question