Faiz Mohamed Haneef Faiz Mohamed Haneef -4 years ago 96
Javascript Question

Passing resolve, reject of outer Promise to inner Promise

I have a basic promise code which works as below



new Promise(function(resolve, reject) {
new Promise(function(resolveInner, rejectInner) {
// do something
resolveInner('resolved inner promise')
}).then(function(msg) {
console.log(msg);
// do something
resolve("resolved from inner")
}).catch(function(msg) {
console.log('error' + msg)
})
}).then(function(msg) {
console.log(msg)
})





I am trying to refactor and modularize the code by bringing the innerResolve function outside like below. This errors out as 'resolve' is undefined



new Promise(function(resolve, reject) {
new Promise(function(resolveInner, rejectInner) {
// do something
resolveInner('resolved inner promise')
}).then(innerResolve) // externalized here !!!!
.catch(function(msg) {
console.log('error' + msg)
})
}).then(function(msg) {
console.log(msg)
})

function innerResolve(msg) {
console.log(msg);
// do something
resolve("resolved from inner")
}





How do I bring outer Promise resolve to innerResolve function?

One solution is to create a global variable which could be set to outer promise resolve for example.



var _resolve;
new Promise(function(resolve, reject) {
_resolve = resolve
new Promise(function(resolveInner, rejectInner) {
// do something
resolveInner('resolved inner promise')
}).then(innerResolve).catch(function(msg) {
console.log('error' + msg)
})
}).then(function(msg) {
console.log(msg)
})

function innerResolve(msg) {
console.log(msg);
// do something
_resolve("resolved from inner")
}





Is there a better approach without global variables?

Answer Source

Your situation seems really convoluted, so you might want to re-evaluate why you need to do this at all, but if it is simply experimenting, you can solve this without globals, by passing the appropriate resolver to a function generator. For example:

const innerResolve = resolver => msg => {
  console.log(msg);
  // do something
  resolver("resolved from inner")
}

new Promise(function(resolve, reject) {
  new Promise(function(resolveInner, rejectInner) {
    // do something
    resolveInner('resolved inner promise')
  }).then(innerResolve(resolve)).catch(function(msg) {
    console.log('error' + msg)
  })
}).then(function(msg) {
  console.log(msg)
})    

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download