Search code examples
node.jsasynchronousrecursioncallbackwait

How to wait callback inside recursive function


I have a recursive function:

let main = () => {
  ftp(_defaultPath, _start, (file, doc, name) => {
    parser(file, doc, name)
  })
}

The parser function:

module.exports = async function (file, doc, name) {
    await funcOne(file, doc)
    await funcTwo(file, doc, name)
    await funcThree(file, doc, name)
}

The callback its called inside the recursive function multiple times:

async function myFuntion(path, name, callback) {
   ...
   callback(file, doc, files[p][1])
   ...
}

The problem is I want to wait when i do callback like:

async function myFuntion(path, name, callback) {
   ...
   await callback(file, doc, files[p][1])
   ... next lines need to wait to finish callback
}

I trying to find how to do that.

It's possible to do that? thanks


Solution

  • I have done on this way:

    I edit my main function with async inside ftp function:

    let main = () => {
      ftp(_defaultPath, _start, async (file, doc, name) => {
        await parser(file, doc, name)
      })
    }
    

    I added the promise to parser function like that:

    module.exports = function (file, doc, name) {
        return new Promise( async (resolve, reject) => {
            try {
                await funcOne(file, doc)
                await funcTwo(file, doc, name)
                await funcThree(file, doc, name)
            } catch(e) {
                return reject(e)
            }
            return resolve()
        }
    }
    

    Inside the recursive function I do the await.

    await callback(file, doc, files[p][1])
    

    Now waits as expected.

    Thanks!