And*_*ich 6 node.js promise async-await
function first(){
console.log('first')
}
function second(){
console.log('second')
}
let interval = async ()=>{
await setInterval(first,2000)
await setInterval(second,2000)
}
interval();
Run Code Online (Sandbox Code Playgroud)
假设我上面有这段代码。
当我运行它,first()并second()会在同一时间被调用; 返回一些数据second()后如何调用first)(),例如,如果first()完成,则仅调用call second()?
因为first()在我的代码中将处理大量数据,并且如果同时调用这两个函数,则对于服务器而言将非常困难。
second()每当何时first()返回一些数据我该如何调用?
Mad*_*iha 10
您有一些问题:
setInterval()意味着要多次调用回调,Promise不能很好地支持这种情况。setInterval()更恰当的setTimeout()回报承诺都不await是没有意义的。您正在寻找一个返回Promise的函数,该函数会在一段时间后解析(使用setTimeout(),可能不是setInterval())。
幸运的是,创建这样的函数相当简单:
async function delay(ms) {
// return await for better async stack trace support in case of errors.
return await new Promise(resolve => setTimeout(resolve, ms));
}
Run Code Online (Sandbox Code Playgroud)
使用此新delay功能,您可以实现所需的流程:
function first(){
console.log('first')
}
function second(){
console.log('second')
}
let run = async ()=>{
await delay(2000);
first();
await delay(2000)
second();
}
run();
Run Code Online (Sandbox Code Playgroud)
mdi*_*ici 10
如前所述,如果您不停止setInterval承诺,将不能很好地兑现承诺。如果您清除间隔,可以像这样使用它:
async function waitUntil(condition) {
return await new Promise(resolve => {
const interval = setInterval(() => {
if (condition) {
resolve('foo');
clearInterval(interval);
};
}, 1000);
});
}
Run Code Online (Sandbox Code Playgroud)
以后你可以像
const bar = waitUntil(someConditionHere)
Run Code Online (Sandbox Code Playgroud)
setInterval与 Promise 配合不好,因为它会多次触发回调,而 Promise 会解析一次。
看来确实是setTimeout符合这个情况的。它应该被承诺以便与以下一起使用async..await:
async () => {
await new Promise(resolve => setTimeout(() => resolve(first()), 2000));
await new Promise(resolve => setTimeout(() => resolve(second()), 2000));
}
Run Code Online (Sandbox Code Playgroud)