Sam H
Sam H

Reputation: 561

How to wait for a specific result in an function while running other functions

I want to run some code while waiting for another response?

Example:

var obj = {};

await pre(obj);
await first(obj);
await second(obj);
await third(obj);

await function pre(obj) {self.something = "something";}
await function first(obj){...something...}
await function second(obj){...something...}
await function third(obj){...Do something with obj...}

What I can't figure out is, how do I run pre() and do its time-consuming objective, while running first() and second() and third() but third will run when pre has finished?

Upvotes: 2

Views: 105

Answers (3)

djheru
djheru

Reputation: 3719

var obj = {};

async function pre(obj) {self.something = "something";}
async function first(obj){...something...}
async function second(obj){...something...}
async function third(obj){...Do something with obj...}

// use array destructuring to get the responses after promises resolve
const [ preResponse, firstResponse, secondResponse ] = await Promise.all([
  pre(obj),
  first(obj),
  second(obj)
]);
const thirdResponse = await third(obj);

Upvotes: 0

Jimmy Leahy
Jimmy Leahy

Reputation: 666

What I can't figure out is, how do I run pre() and do its time-consuming objective, while running first() and second() and third() but third will run when pre has finished?

Based on this question, it is my understanding that you want to:

  1. Run pre, first and second simultaneously
  2. Once pre has finished executing, then run third

If this is the case then the following code will do that :

var obj = {test: "Test"};

async function pre(obj) {console.log(`${pre.name} :`, obj); return obj;}
async function first(obj)  {console.log(`${first.name} :`, obj)}
async function second(obj) {console.log(`${second.name} :`, obj)}
async function third(obj)  {console.log(`${third.name} :`, obj)}

Promise.all([first(obj), second(obj), pre(obj).then(third)]);

The Promise.all() function takes an array of functions that return a promise and executes them in parallel. Notice the pre(obj).then(third). This will execute the pre function and upon completion will execute the third function.

Upvotes: 0

jakemingolla
jakemingolla

Reputation: 1639

You could use Promise.all to run all of your intermediary steps in parallel before running third:

var obj = {};

await Promise.all([ pre(obj), first(obj), second(obj)]);
await third(obj);

If I'm understanding your question correctly, at by the time the Promise.all has finished, obj will contain the mutations of running pre, first, and second.

Be careful about error handling as well as nondeterministic access to the obj object.

Upvotes: 4

Related Questions