[英]How to correctly set async recursion in node.js?
這是一個示例函數。
async function getRandomBig() {
let result;
result = await randomModule.getRandom();
if (result > 0.9 ) {
return getRandomBig();
} else {
return result;
}
}
因此,顯然,我希望對randomModule.getRandom()
執行異步發生。 這個例子走了嗎?
另外,我想知道如何使對getOutput的第一個調用是異步的。
謝謝
根據您提供的信息,很難回答您的問題,但這也許會有所幫助:
異步函數將向外部調用者返回一個承諾。 比意味着從await
獲得的結果將異步發生。 例如,考慮以下代碼:
// normal synchronous function function changeRes() { return "after" } // sync function that `awaits` it's result async function getget() { res = await changeRes() } let res = "before" // p will be a pending promise var p = getget() // what is res at this point? console.log(res) // still "before" because await doesn't return until next tick // now res is 'after' p.then(() => console.log(res))
但是要小心,因為對changeRes
的調用不是異步的,而是在當前循環中調用的。 將此與第一個代碼進行比較。 我們只更改changeRes()
的行為:
function changeRes() { res = "after" return res } async function getget() { res = await changeRes() } let res = "before" // p is still a pending promise var p = getget() // but res was changed in changeRes synchronously console.log(res) p.then(() => console.log(res))
根據評論進行編輯:
使用遞歸函數,所有重要的事情都在異步函數內部發生,因此它們都應該按預期工作。 例如,您可以將您的randomModule.getRandom
替換為同步的常規Math.random()
,但是await
將使其在異步函數的上下文中工作。 因此,此函數將返回一個承諾,該承諾將解析為小於0.25的隨機浮點數:
async function getRandomBig() { let result; result = await Math.random(); if (result > 0.25) { return getRandomBig(); } else { return result; } } getRandomBig().then(console.log)
即使它確實是異步的,也是如此:
function asyncRandom(){ return new Promise(resolve => { setTimeout(() => resolve(Math.random()), 500) }) } async function getRandomBig() { let result; result = await asyncRandom(); if (result > 0.25 ) { console.log("too big recurse") return getRandomBig(); } else { return result; } } getRandomBig().then(console.log)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.