将 Promise.then() 内的递归调用转换为循环?

我需要在 .then() 方法内递归调用函数本身。像这样的东西:


function poll(params) { 

    const returned_promise = read_from_backend(some_url, some_params);

    returned_promise

       .then(some_process_func)

       .then(r => {

            poll(some_params); // recursive call

        })   

}


poll(starting_params);

有没有办法在 while 循环中编写这个算法,而不阻塞主线程?


大话西游666
浏览 91回答 1
1回答

不负相思意

这是一种用 while 循环编写算法的方法。由于我们通过 Promises 处理异步代码,因此我们不会阻塞主线程。async function poll(params) {    while (true) {        await new Promise(resolve => setTimeout(resolve, 1000)) // perhaps sleep a bit between polls        const returned_promise = read_from_backend(some_url, some_params);        const r = await returned_promise.then(some_process_func)    }}poll(starting_params);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript