首页 文章

NodeJS - 等待在setTimeout内返回

提问于
浏览
1

我正在尝试学习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() 但它在第一次调用函数后立即触发 . 我怎么能等待那次回归?

1 回答

  • 2

    你永远不应该从异步(非承诺)回调或inside the new Promise constructor调用一个promise-returns函数,比如 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');
    }
    

相关问题