Search code examples
javascriptasynchronouspromisecallbacknested-function

async function nested inside a function


I'm using a framework where I found code like this:

block1

fun_1(params, callback) { 
        fun_2(params, callback) {
                ...     
                     fun_n(params, callback) {
                          asyncFunction().then(callback).catch(callback)
                                }

as asyncFunction is from a deprecated npm package i would take the opportunity to refactor it. I would like to switch to something like this:

block2

fun_1(params).then(callback)

Where fun_1 would be:

fun_1(params) {
    fun_2(params) {
          return asyncFunc()     ???
  }
}   

Is the second pattern correct and preferable over the first ?


Solution

  • It seems correct. However, all functions need to return that promise when they call the inner function. For example:

    fun_1(params) {
      fun_2(params) {
        return asyncFunc();
      }
    
      return fun_2(params);
    } 
    
    fun_1(params).then(callback);