所以我有5个需要立即运行的函数。但是在一个功能完成后终止所有功能。有可能的?我已经搜索过但没有找到与我的问题有关的任何答案。
答案 0 :(得分:0)
您可以使用Promise.race
。
带有Promise.race
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function func() {
return new Promise((resolve) => {
const time = getRandomInt(1000, 3000);
console.log(`Function terminate in ${time} ms`);
setTimeout(() => resolve(), time);
});
}
let time = Date.now();
(async() => {
const time = Date.now();
await Promise.race([
func(),
func(),
func(),
]);
console.log(`Over after ${Date.now() - time} ms`);
})();
带有Promise.all
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function func() {
return new Promise((resolve) => {
const time = getRandomInt(1000, 3000);
console.log(`Function terminate in ${time} ms`);
setTimeout(() => resolve(), time);
});
}
(async() => {
let time = Date.now();
await Promise.all([
func(),
func(),
func(),
]);
console.log(`Over after ${Date.now() - time} ms`);
})();