最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Run a second function only after the first function is completely finished - Stack Overflow

programmeradmin3浏览0评论

Hi everyone I have such a problem, I have 2 asynchronous functions. I want only after the first is pletely 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();

Hi everyone I have such a problem, I have 2 asynchronous functions. I want only after the first is pletely 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.

Share Improve this question edited Apr 18, 2021 at 15:27 hch asked Apr 18, 2021 at 15:18 hchhch 7571 gold badge7 silver badges18 bronze badges 3
  • 1 I can't seem to reproduce your issue - via the snippet runner at least – richytong Commented Apr 18, 2021 at 15:22
  • 1 firstFunc and secondFunc are not promises – Mister Jojo Commented Apr 18, 2021 at 15:22
  • @MisterJojo Thanks for the ment, how can this be turned into promises? – hch Commented Apr 18, 2021 at 15:27
Add a ment  | 

5 Answers 5

Reset to default 5

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
});

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

  • Async/await: https://javascript.info/async-await
  • Promise: https://javascript.info/promise-basics

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();
}

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();

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 pleted its execution. I hope this helps...

发布评论

评论列表(0)

  1. 暂无评论