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

标签 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 的第一次调用异步。

谢谢

最佳答案

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

异步函数将向外部调用者返回一个 promise 。 Than 意味着从 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 会使其正常工作在异步函数的上下文中。所以这个函数将返回一个 promise ,解析为小于 0.25 的随机 float :

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)

关于javascript - 如何在node.js中正确设置异步递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49743010/

相关文章:

javascript - 将 nodejs/express 应用程序中的 json 文件加载到 d3

node.js - Node.JS 音频混合 + MP3 生成可能吗?

javascript - "export ' __platform_browser_private__ ' was not found in ' @angular/platform-b​​rowser'

javascript - 在extjs中合并两个不同的json对象

javascript - 来自包装在服务中的外部 HTTP API 的数据绑定(bind)不起作用

javascript - 套接字 : How to perform certain action while reconnecting after disconnection?

node.js - 如何在 Sequelize 中创建表以使用 Node JS 存储在 Postgresql 中

javascript - Axios 返回未决 promise

c# - 如果我们在 ASP.NET Core 中等待长时间的异步操作,可能会出现什么问题?

node.js - 使用 Twitter API 的异步 - Await 问题