Tree
Tree

Reputation: 31361

How to correctly set async recursion in node.js?

Here is one example function.

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

So Obviously, I would like that execution to randomModule.getRandom() happens asynchronously. Is this example the way to go?

Also, I would like to know how to make the first call to getOutput be asynchronous.

Thank you

Upvotes: 0

Views: 64

Answers (1)

Mark
Mark

Reputation: 92440

It's a little hard to answer your question given the info you've provided, but maybe this will help:

The async function will return a promise to the outside caller. Than means that results obtained from await will happen asynchronously. For example consider this code:

// 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))

But be careful because the call to changeRes is not asynchronous — it is called in the current loop. Compare this with the first code. We only change the behavior of 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))

EDIT based on comment:

With the recursive function, everything important is happening inside the async function, so it all should work as expected. For example, you can substitute your randomModule.getRandom with the regular Math.random() which is synchronous, but the await will make it work in the context of an async function. So this function will return a promise that resolves to a random float less than 0.25:

async function getRandomBig() {
  let result;
  result = await Math.random();
  if (result > 0.25) {
    return getRandomBig();
  } else {
    return result;
  }
}

getRandomBig().then(console.log)

So will this even though it's truly async:

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)

Upvotes: 2

Related Questions