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:(用回调来做到这一点将是一件令人头疼的事,但是使用promise却是小菜一碟:)
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.(与try { ... } catch
块几乎相同。)
Even better:(更好的是:)
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.
});
And even better: What if those 3 calls to api
, api2
, api3
could run simultaneously (eg if they were AJAX calls) but you needed to wait for the three?(甚至更好:如果这三个对api
, api2
和api3
可以同时运行(例如,如果它们是AJAX调用),但您需要等待这三个调用怎么办?)
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:(使用ES6表示法的承诺,是又轻松又整洁的事情:)
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.
});
Hope you see Promises in a new light now.(希望您现在看到一个崭新的承诺。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…