gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:14:31 26 4
gpt4 key购买 nike

大家好,我有这样的问题,我有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com