如何在node.js中正确设置异步递归?

时间:2018-04-09 23:14:51

标签: javascript node.js async-await

这是一个示例函数。

async function getRandomBig() {
    let result;
    result = await randomModule.getRandom();
    if (result > 0.9 ) {
        return getRandomBig();
    } else {
        return result;
    }
}

所以显然,我希望randomModule.getRandom()的执行是异步发生的。这个例子是要走的路吗?

另外,我想知道如何第一次调用getOutput是异步的。

谢谢

1 个答案:

答案 0 :(得分:2)

根据您提供的信息,回答您的问题有点难,但也许这会有所帮助:

异步函数将向外部调用者返回一个promise。比意味着从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)

相关问题