我有一个基本的承诺代码,如下所示
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)
})

我试图通过将innerResolve函数放在外部来重构和模块化代码,如下所示。这会导致错误,并且会解决问题。未定义
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")
}

如何将外部Promise解析带入innerResolve函数?
一种解决方案是创建一个全局变量,例如可以设置为外部承诺解析。
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")
}

没有全局变量是否有更好的方法?
答案 0 :(得分:2)
你的情况似乎真的很复杂,所以你可能想要重新评估你为什么需要这样做,但如果只是试验,你可以通过将适当的解析器传递给函数生成器来解决这个问题而不用全局变量。例如:
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)
})