【问题标题】:NodeJS - Wait for return inside setTimeoutNodeJS - 在 setTimeout 内等待返回
【发布时间】:2018-12-09 13:15:43
【问题描述】:

我正在尝试学习异步/等待。我想在我的异步函数中等待返回语句。我必须多次调用它,所以我在里面使用了 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(),但它在第一次调用该函数后立即触发。我怎样才能等待返回?

【问题讨论】:

  • 你需要承诺setTimeout。然后你可以在一个循环中await它。
  • 您能详细说明一下吗?我刚刚阅读了 nodejs 文档,但我不明白。该示例在第一次 setTimeout 调用后执行代码
  • 没关系,我明白了,非常感谢!我会发布我的解决方案
  • @Bergi 看起来我评论得有点快。你还能帮忙吗?
  • 你能edit这个问题来展示你的尝试吗?也许你走在正确的道路上。

标签: javascript node.js async-await return settimeout


【解决方案1】:

您永远不应该从异步(非承诺)回调或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');
}

【讨论】:

  • 干得好@Bergi!
  • 这就像一个魅力!我从没想过使用while 循环,再次感谢!
猜你喜欢
  • 1970-01-01
  • 2019-07-25
  • 2011-08-16
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多