async function nested inside a function

1.1k Views Asked by At

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 ?

2

There are 2 best solutions below

2
On BEST ANSWER

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);
2
On

There's not much information in your question, but I'll try to answer with what I have.

In order for fun_1 to be able to be chained with .then, it needs to return a promise:

function fun_1() {
   return new Promise((resolve, reject) => {
      // Do some tasks and resolve when complete
      resolve(/* some data */)
   }
}

Or, by using the async keyword, which is just syntactic sugar for Promise:

async function fun_1() {
    await some_async_task()
    return; // does the same as resolve would in Promise
}

In order to refactor the code, you're going to have to move the async stuff and the callbacks in promises. Let me know if you want to clarify some things in your question to get a better answer.