NodeJS - 在 setTimeout 中等待 return
NodeJS - Wait for return inside setTimeout
我正在努力学习async/await。我想在异步函数中等待 return 语句。我必须多次调用它,所以我在里面使用了 setTiemout。
编辑:
//Processing gallery
async function somefunction(){
async function getPictureR(){
/* some code */
if($('.actions > .prev', html)[0]){
older = $('.actions > .prev', html)[0].attribs.href;
} else {
console.log('return');
return;
}
/* some code */
return new Promise((resolve, reject) => {
setTimeout(getPictureR, 1 * 1000/2);
})
}
await getPictureR();
console.log('getPictureR done');
}
我试过 await getPictureR()
但它在第一次调用该函数后立即触发。我怎么能等到 return 呢?
您永远不应该从异步(非承诺)回调或 inside the new Promise
constructor 中调用承诺返回函数,例如 getPictureR
。您也从未解决 new Promise
。您正在寻找
return new Promise((resolve, reject) => {
setTimeout(resolve, 1 * 1000/2);
}).then(() => {
return getPictureR(); // do the promise call in a `then` callback to properly chain it
})
但是由于您正在使用 async
/await
,因此您不需要递归函数和 then
链接。您还可以在单独的辅助函数中分解出 setTimeout
-in-promise 包装:
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
async function somefunction() {
while (true)
/* some code */
const prev = $('.actions > .prev', html);
if (prev.length) {
older = prev[0].attribs.href;
} else {
console.log('return');
break;
}
/* some code */
await delay(1 * 1000/2);
// ^^^^^^^^^^^
}
console.log('getPicture done');
}
我正在努力学习async/await。我想在异步函数中等待 return 语句。我必须多次调用它,所以我在里面使用了 setTiemout。
编辑:
//Processing gallery
async function somefunction(){
async function getPictureR(){
/* some code */
if($('.actions > .prev', html)[0]){
older = $('.actions > .prev', html)[0].attribs.href;
} else {
console.log('return');
return;
}
/* some code */
return new Promise((resolve, reject) => {
setTimeout(getPictureR, 1 * 1000/2);
})
}
await getPictureR();
console.log('getPictureR done');
}
我试过 await getPictureR()
但它在第一次调用该函数后立即触发。我怎么能等到 return 呢?
您永远不应该从异步(非承诺)回调或 inside the new Promise
constructor 中调用承诺返回函数,例如 getPictureR
。您也从未解决 new Promise
。您正在寻找
return new Promise((resolve, reject) => {
setTimeout(resolve, 1 * 1000/2);
}).then(() => {
return getPictureR(); // do the promise call in a `then` callback to properly chain it
})
但是由于您正在使用 async
/await
,因此您不需要递归函数和 then
链接。您还可以在单独的辅助函数中分解出 setTimeout
-in-promise 包装:
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
async function somefunction() {
while (true)
/* some code */
const prev = $('.actions > .prev', html);
if (prev.length) {
older = prev[0].attribs.href;
} else {
console.log('return');
break;
}
/* some code */
await delay(1 * 1000/2);
// ^^^^^^^^^^^
}
console.log('getPicture done');
}