1

I'm using async await via babel-plugin-transform-async-to-generator.

At the top-level I'm awaiting a function response. Then there another two async functions func1 and func2. func2 asynchronously retrieves the content of https://www.google.com.

The following script returns:

go() called
func1() called
finished
func2() called
func2() called
func2() called

How can I only console.log('finished') after all call are executed successfully? Is it possible without returning them explicitly as Promises using resolve/reject?

This example is greatly simplified. What I'm trying to do involves recursive function calls I'd to await as well

const rp = require('request-promise')

go()

async function go() {
  console.log("go() called")
  await func1([1,2,3])
  console.log("finished the script")
}

async function func1(arr) {
  console.log("func1() called")
  arr.forEach(async function(element) {
    await func2()
  })
}

async function func2() {
  var res = await rp('https://www.google.com')
  console.log("func2() called")
}
Hedge
  • 16,142
  • 42
  • 141
  • 246
  • `console.log("finished the script")` does not wait for `await func1([1,2,3])` ? You can alternatively use `Promise.all()` – guest271314 Aug 13 '16 at 22:00
  • Can you have two `await`s in the same function? If yes, probably you have to remove the `async` keyword from inside the `forEach` loop. (I never used async/await) – XCS Aug 13 '16 at 22:01
  • @guest271314 In my original code there are recursive function calls involved where one call relies on the result of the former one. – Hedge Aug 13 '16 at 22:03
  • `Promise.all()` should be able to have recursive calls. See http://stackoverflow.com/questions/37089515/promise-all-inside-a-foreach-loop-everything-firing-at-once, http://stackoverflow.com/questions/37089515/promise-all-inside-a-foreach-loop-everything-firing-at-once – guest271314 Aug 13 '16 at 22:12
  • There is no "deep" with async/await. You have to return promises from every asynchronous function to be able to `await` it, there is no way around that. Including functions that take asynchronous callbacks. – Bergi Aug 14 '16 at 19:51

1 Answers1

0

I'm still not sure how to do this for recursive calls but will create a separate question / example for it.

The above example can be fixed by using for..of instead of forEach. The inner functions results can't be awaited.

const rp = require('request-promise')

go()

async function go() {
  console.log("go() called")
  await func1([1,2,3])
  console.log("finished the script")
}

async function func1(arr) {
  console.log("func1() called")

  for (let item of arr) {
    await func2()
  }
}

async function func2() {
  var res = await rp('https://www.google.com')
  console.log("func2() called")
}
Hedge
  • 16,142
  • 42
  • 141
  • 246