【发布时间】:2020-07-20 22:23:48
【问题描述】:
我发现 Javascript Promise 并不多。
但是,我发现了一种我无法理解的关于在 Promises 中嵌套(新的或返回的)Promise 的行为
这是背景(extPromiseX是第三方函数返回Promise):
案例一:
function myAction(param) {
return extPromise1(sql).then((result) => {
[...]
return extPromise2(sql2).then((result) => {
[...]
return extPromise3(sql3);
})
});
}
// Main Process
myAction(...)
.then(() => {
console.log('Process Terminated');
}).catch((error) => {
console.error('Exit with error', error);
});
现在,正如预期的那样,我从控制台得到,在
1) extPromise1 completed
2) extPromise2 completed
3) extPromise3 completed
4) Process Terminated
案例2:
function myAction(param) {
return new Promise(function() {
if (itsAllOkWithInputs) {
// Some sync code here
return extPromise1(sql).then((result) => {
[...]
return extPromise2(sql2).then((result) => {
[...]
return extPromise3(sql3);
})
})
} else {
throw 'Something went wrong';
}
});
}
// Main process
myAction(...)
.then(() => {
console.log('Process Terminated');
}).catch((error) => {
console.error('3) --> Exit with error', error);
})
在第二种情况下,extPromises 被执行,但第一个 Promise 仍然挂起(由调试确认)。所以控制台显示:
1) extPromise1 completed
2) extPromise2 completed
3) extPromise3 completed
我凭经验意识到我必须更改 myAction 函数,代码才能正常工作:
function myAction(param) {
return new Promise(function(resolve, reject) {
if (itsAllOkWithInputs) {
// Some sync code here
let ep = extPromise1(sql).then(...);
resolve(ep);
} else {
throw 'Something went wrong';
}
});
}
我的问题:
我认为在另一个父母中返回一个承诺会做出
父母解决孩子的结果。这是这种情况
在应用于外部承诺的then 代码块内。为什么
这对new Promise 案例无效?
【问题讨论】:
-
案例2:在promise构造函数中返回没有意义..您需要在promise构造函数中解析或拒绝,但是,由于构造函数中的代码已经有一个promise,所以不要使用Promise 构造函数反模式
-
@JaromandaX:
myAction必须返回一个Promise,但是,在调用外部的之前,我必须对输入进行检查。这就是我采用 Promise 构造函数的原因。有什么不同的解决方案吗? -
是的,承诺链,你知道...
.then(....).then(....)等
标签: javascript promise