【发布时间】:2020-11-09 10:58:22
【问题描述】:
我有一个节点 js 程序。我想使用 Promise.all 异步运行 2 个倒计时函数。预计两个功能会一起倒计时,程序在5秒内结束。但它们按顺序运行,程序在 10 秒内结束。如何异步运行它们?感谢您的帮助。
const delayOneSecond = () => {
let start = new Date().getTime();
while (new Date().getTime() - start < 1000) { }
return;
}
const OK = true;
const func = (name, num) => {
return new Promise(
function (resolve, reject) {
if (OK) {
for(let i=1; i<=num; i++){
delayOneSecond();
console.log(`[${name}] - ${num - i}`);
}
resolve('OK');
} else {
reject(new Error('Not OK'));
}
});
}
Promise.all([func('xxx', 5), func('ooo', 5)])
.then((res) => { console.log(res); })
【问题讨论】:
-
你的代码没有异步,所以它是同步运行的。 Promise 不会使代码异步,它们将异步调用的处理抽象为易于管理的形式。要使其异步运行,您需要添加本质上是异步的东西,即 ajax 调用或 setTimeout 等。
标签: javascript node.js asynchronous promise