且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不是承诺只是回调?

更新时间:2023-10-30 18:00:22

Promise不是回调。 promise代表异步操作的未来结果。当然,写他们的方式你做,你得到的好处。但是如果你写它们的方式,他们的意图使用,你可以编写异步代码的方式类似于同步代码,更容易遵循:

Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});

当然,代码不多,但可读性更高。

Certainly, not much less code, but much more readable.

但这不是结束。让我们来发现真正的好处:如果你想检查任何错误在任何步骤怎么办?它会是回调,但与承诺,是一块蛋糕:

But this is not the end. Let's discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});
Pretty much the same as a try { ... } catch block. 

更好:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
}).then(function() {
     //do something whether there was an error or not
     //like hiding an spinner if you were performing an AJAX request.
});

甚至更好:如果这3个调用 api api2 api3 可以同时运行(例如,如果他们是AJAX调用),但你需要等待他们三个?没有承诺,你应该创建一些计数器。使用ES6符号的承诺是另一块蛋糕,非常漂亮:

And even better: What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:

Promise.all([api(), api2(), api3()]).then(function(result) {
    //do work. result is an array contains the values of the three fulfilled promises.
}).catch(function(error) {
    //handle the error. At least one of the promises rejected.
});

希望你现在看到Promises的新灯光。

Hope you see Promises in a new light now.