0

I need to have a bunch of functions complete some tasks and in a final function do something with the results.

I was thinking of using async / await?

async function dosomething() {
    // do stuff
    // await till finished then grab the result 
}

async function dosomethingelse() {
    // do stuff
    // await till finished then grab the result 
}

function final() {
    if (dosomething_result) {
     // do something
    }

    etc...
}

So basically final() wouldn't run till dosomething and dosomethingelse have completed.

I hope I have explained myself properly.

My question is...How would I do this with Async / Await if it's the way to do this I mean.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

1 Answers1

1

Keep in mind that when you declare a function async, all that's really happening behind the scenes is that the function is going to return a Promise, and the return value of the function will be the value that Promise resolves to.

Since the function returns a Promise, you can use that fact to chain the calls.

For example, if you want a fully sequential execution, you could to this:

dosomething().then(dosomethingelse).then(final)

If you want to parallelize the execution of dosomething and dosomethingelse, wait for both to complete, and only then execute final, you can do something like:

Promise.all([dosomething(), dosomethingelse()]).then(final)

It's just a promise, nothing more. To learn more about what you can do, probably the best thing is to dive deep into promises.

And for students and lovers of CS theory, studying Monads can also be a nice extra - it's a Monad, and the operations on the promises can be seen as monadic operations.

Bruno Reis
  • 37,201
  • 11
  • 119
  • 156