D
D
Dmitry2210602018-03-16 16:23:33
Node.js
Dmitry221060, 2018-03-16 16:23:33

How to make an async function wait for a response from another async function?

Sorry if this is a dumb question, I just started to understand async/await.
There is a function whose callback needs to be executed asynchronously, but it calls another asynchronous function many times -

... .then(async (data) => { //Нужно асинхронно выполнить этот callback
  try {
    let size = data.size;
    data.forEach((message) => {
      if (!message.pinned) {
        await message.delete().catch(writeErr); //message.delete - возвращает Promise
      }
    });
    Send(size + " сообщений удалено"); //Этот вызов должен сработать только после того, как все Promise от message.delete выполнятся
  } catch (err) {
    Send("Извините, произошла ошибка");
    return writeErr(err);
  }
})

This code throws an error -
await message.delete().catch(writeErr);
      ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)

How can I implement my plan and what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmitrygavrish, 2018-03-16
@Dmitry221060

The error is because the function you are passing to forEach is not asynchronous. Those. necessary:

data.forEach(async (message) => {
      if (!message.pinned) {
          await message.delete().catch(writeErr); //message.delete - возвращает Promise
      }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question