hch
hch

Reputation: 757

Run a second function only after the first function is completely finished

Hi everyone I have such a problem, I have 2 asynchronous functions. I want only after the first is completely over, to run the second. This is what I tried to do:

  run2functions = async () => {
    await firstFunc();
    await secondFunc();
  };
  
  firstFunc = () => {
    console.log("first one");
    //Api code for information from any server

 }
 
  secondFunc = () => {
    console.log("second one");
    //Api code for information from any server

 }
 
 run2functions();

But it does not always work, sometimes the code of the second function runs before the code of the first function, I'm not sure why, I used await to force the second to be only after the first one ends.

I only want the first function to end now to activate the second function.

Upvotes: 5

Views: 2602

Answers (5)

Ritik-2000
Ritik-2000

Reputation: 1

async function rango(){

let amp = new Promise(function(resolve,reject){
    setTimeout(function(){
        console.log("First Promise");
    },2000);
 });


let volt = new Promise(function(resolve,reject){
    setTimeout(function(){
        console.log("Second Promise");
    },3000);
});

let a = await amp;
let v = await volt;

return[a,v];

}

rango();

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206102

Make async the functions that are awaitable (return a Promise)

// DEMO ONLY Just a helper to wait some ms time and return a Promise
const wait = (t) => new Promise((r) => setTimeout(r, t)); 

const firstFunc = async () => {
  await wait(1000); // Just to fake some wait time
  console.log("first one");
}

const secondFunc = () => { // This does not need to be async
  console.log("second one");
}

const run2functions = async() => {
  await firstFunc();  // Await for this one
  secondFunc();       // You don't need to await for this one
};

run2functions();

Will result in:

(waiting 1 sec....)   
"first one"
"second one"

If you're waiting for both responses (i.e: one function takes 3sec to resolve, and the other one takes 2sec to resolve):
use Promise.all

// DEMO ONLY Just a helper to wait some ms time and return a Promise
const fakeFetch = (time, data) => new Promise((res, rej) => setTimeout(res, time, data)); 

// Functions that return a Promise (just like JS's fetch());
const one = () => fakeFetch( 3000, {message:"First!"} );
const two = () => fakeFetch( 2000, {message:"Second!"} );

Promise.all([one(), two()]).then((values) => {
  // After 5 sec...
  console.log(values); // In the exact order as the functions calls array
});

A real-world example of the above would be like:

const getJSON = (url) => fetch(url).then(res => res.json()); // Returns a Promise
Promise.all([getJSON("users.json"), getJSON("tasks.json")]).then((JSONs) => {
  // After some unknown time... Both fetch Promises are resolved.  
  // Do some work with both JSON data:
  console.log(JSONs); // In the exact order as the functions calls array
});

Upvotes: 5

Kaif Ahmad
Kaif Ahmad

Reputation: 26

function run2functions() {
    firstFunc(secondFunc);
}

function firstFunc(cb) {
    setTimeout(() => {
    },1000);
    cb();
    console.log("first one");
}

function secondFunc() {
    setTimeout(() => {
        console.log("second one");
    },1000);
}
 
run2functions();
I have used the callback function for asynchronous operation. I have used setTimeOut function in both the firstFunct and secondFunct to prove my point that the secondFunct only executes after the firstFunct has completed its execution. I hope this helps...

Upvotes: -1

iagowp
iagowp

Reputation: 2494

If function one doesn't explicitly return a promise, and runs some async code, you can run into the situation you are describing.

You can solve this in two forms:

1 - Make firstFunc async and make it only finish after all code has run

const firstFunc = async () => {
  await getApiResponse();
  ...
}

2 - Make firstFunc return a Promise, that will make your main function properly await for it before moving on

const firstFunc = () => {
  return getApiResponse();
}

Upvotes: 2

Tonnio
Tonnio

Reputation: 655

Async/await works only with fuctions which return Promise. So your code should look something like that:

const run2functions = async () => {
  await firstFunc();
  await secondFunc();
};

const firstFunc = () => {
  return new Promise((res) => {
    // your async code here
    console.log("first one");
    resolve(res);
  });
};

const secondFunc = () => {
  return new Promise((res) => {
    // your async code here
    console.log("second one");
    resolve(res);
  });
};

await run2functions();

Additional resources

Upvotes: 2

Related Questions