gpt4 book ai didi

javascript - 在 js 中执行完前两个异步函数后需要执行第三个异步函数吗?

转载 作者:行者123 更新时间:2023-11-30 15:52:02 25 4
gpt4 key购买 nike

条件

first two async functions start at the same time
don't know which one finish first

需要在这两个完成时执行第三个函数。

尝试使用 promise 。如果可能,请使用 promise 和其他方式帮助实现它。

有些东西我试过不确定是否正确...

function foop(a){
return new Promise(function(resolve, reject){
window.setTimeout(function(){
console.log("first promise executed");
}, 2000);
window.setTimeout(function(){
console.log("second promise executed");
if(a>5) resolve(a+10);

}, 2000);

if(a<5) reject("error");
});
}

foop(12).then(function(val){
window.setTimeout(function(){
console.log("first then executed -"+ val);
}, 1000);
}).then(function(val){
window.setTimeout(function(){
console.log("second then executed -"+ val);
}, 500);
}).catch(function(err){
console.log("error occured");
});

预期的输出顺序

first promise executed      //or second promise executed
second promise executed // or first promise executed
first then executed -22 //only executed after first two async completes in any order
second then executed -22 // execute after the third async completes (first then completes)
error occured // in case of reject

最佳答案

使用Promise.all :

console.log('starting...');

// example function: sleep for 'delay' ms then resolve to 'value'
const wait = (delay, value) => new Promise((resolve, reject) => setTimeout(() => { console.log('done:', value); resolve(value); }, delay));

// start two async functions at the same time
// (in this case, they complete in random order)
const firstPromise = wait(900 + 200 * Math.random(), 'first');
const secondPromise = wait(900 + 200 * Math.random(), 'second');

// Promise.all will wait until all promises given are resolved:
Promise.all([ firstPromise, secondPromise ])
.then((results) => {
// if all promises are resolved, results is an array of the
// result values from each, in the order they are given

console.log(results); // = [ 'first', 'second' ]

// run some other function again...
return wait(500, 'third');
})
.then((result) => {
// 'result' is the result from the third function

// more functions, etc...
return wait(800, 'fourth');
})
.then((result) => {

// you can even use Promise.all again to run two functions simultatenously, inside a .then
return Promise.all([
wait(1100, 'fifth'),
wait(900, 'sixth')
]);
})
// etc...
.catch((error) => {
// if any promise fail, error will be the error from the first to fail

console.error('Error:', error);
});

关于javascript - 在 js 中执行完前两个异步函数后需要执行第三个异步函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171123/

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