我想知道为什么BlueBird要在promise的回调中有动作。像这样:
var pr = new Promise(function(successCb, errorCb){
// do what you need
successCb();
});
pr.then(function(){
// react to promise resolved
});我被期望有一个类似如下的流程:
var pr = new Promise;
// do what you need
pr.resolve();
pr.then(function(){
// react to promise resolved
});我不明白为什么为避免回调而设计的模式要求我使用回调。这是出于特定原因而需要的吗?
发布于 2015-12-02 22:26:46
承诺不是为了避免回调,而是(在其他事情中)防止回调地狱,并使错误捕获更容易。
doAsync1(params, function(err, res) {
if (err) {
throw new Error(err);
}
doAsync2(res1, function(err, res2) {
if (err) {
throw new Error(err);
}
doAsync3(res2, function(err) {
if (err) {
throw new Error(err);
}
// then do stuff
}
}
}在promisified的土地上,...will是这样写的:
doAsync1(params)
.then(function(res1) {
return doAsync2(res1);
})
.then(function(res2) {
return doAsync3(res2);
})
.then(function(res3) {
// Do something
})
.catch(err) {
throw new Error(err);
});你可以找到more details here
编辑:所以你是对的:在没有回调的同步代码中,Promise是无用的。
发布于 2015-12-09 19:21:43
回调是由另一个函数调用的任何函数,该函数将第一个函数作为参数。它在函数内部某个指定点被“回调”。当我们讨论javascript时,我们一直在处理回调。
你不能避免回调,它们是node js库的核心。它们实现了跨应用程序的平衡、非阻塞的控制流,它们几乎是所有promise库的基础。在您的代码中,传递给then的函数只是一个回调函数。
Promise实际上是一种不同的风格,可以达到与回调相同的效果。这里的优点是抽象,这使得使用回调非常令人愉快。
您可以通过这些链接更好地掌握这些概念:
https://stackoverflow.com/questions/34044869
复制相似问题