Search code examples
javascriptasynchronousecmascript-2016

How to await a previously-started function in ES7?


I have two asynchronous methods that return values, one of which is needed immediately and the other might be in use, based on the first result. However, I don't want to wait for the first result to come in before kicking off the second method and create an execution sequence dependency.

Using ES7 syntax, I would assume that await-ing a Promise would be the same as await-ing a function that returns a Promise, but it doesn't work:

async function tester() {
    async function foo() { await setTimeout(() => {}, 2000)}
    async function bar() { await setTimeout(() => {}, 1000)}
    let rcFoo = foo();
    let rcBar = await bar();
    if (true) { // Some conditional based on rcBar
        await rcFoo;
        console.log(rcFoo); // It's a Promise object
    }
}

Two questions:

  1. Am I even understanding the asynchronous nature of Javascript correctly? If the above code would have worked, would it have achieved my goal of running two asynchronous functions concurrently-ish, or is it just not possible to do it?
  2. Is it possible to somehow await an object that is a Promise like I tried, or does it have to reference a function directly?

Thanks..


Solution

    1. In your code, foo will start right away, and then bar will start. Even if foo finished first, your code still awaits for the bar promise to finish before proceeding.
    2. You can await everything as long as it's a promise, whether it's a variable or a returned value from a function call. As far as I know (I might be wrong), setTimeout doesn't return a promise, but it would be easy to convert it to one:

      async function foo() {
        return new Promise(resolve => setTimeout(resolve, 2000))
      }
      async function bar() {
        return new Promise(resolve => setTimeout(resolve, 1000))
      }