所以我有5个功能,我需要立即运行它。但是在一个函数完成后终止所有函数。有可能的?我搜索过但没有找到任何与我的问题相关的答案。
你可以使用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`);
})();