javascript - 只有在第一个功能完全完成后才运行第二个功能

标签 javascript asynchronous async-await

大家好,我有这样的问题, 我有 2 个异步函数。 我只想在第一个完全结束后运行第二个。 这是我尝试做的:

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

但它并不总是有效,有时第二个函数的代码在第一个函数的代码之前运行,我不确定为什么,我使用 await 强制第二个仅在第一个函数结束后运行。

我现在只希望第一个功能结束以激活第二个功能。

最佳答案

使 async 函数可以await(返回一个 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();

将导致:

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

如果您正在等待两种响应(即:一个函数需要 3 秒才能解析,而另一个函数需要 2 秒才能解析):
使用 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
});

上面的真实世界示例如下:

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

关于javascript - 只有在第一个功能完全完成后才运行第二个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67150171/

相关文章:

asp.net - Jquery自动完成加载问题

c# - ContinueWith 作为 await 运算符的替代

c#-4.0 - 继续取消任务

C# 获取异步任务

c# - 从 await 返回后的意外行为

javascript - 等待 _app.js 加载,然后在 Next.js 上运行组件

javascript - 异步等待的问题

javascript - 如何在 C# 代码中使用 jQuerydialog() 而不是confirm()?

javascript - Sequelize 更新信息

javascript - 更改 SVG 内容时保留 d3 缩放状态?