[英]convert recursive calling inside Promise.then() into a loop?
我需要在 a.then() 方法中遞歸調用 function 本身。 像這樣:
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 循環中編寫這個算法,而不阻塞主線程?
下面是一種使用 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.