小编典典

JavaScript不只承诺回调吗?

javascript

我已经开发JavaScript几年了,我完全不了解关于promise的麻烦。

看来我所做的就是改变:

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

无论如何我都可以使用像async这样的库,它有类似以下内容:

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

哪个代码更多,可读性更差。我在这里什么都没得到,也不是突然变得神奇地“平坦”。更不用说必须将事情变成诺言。

那么,这里的诺言有什么大惊小怪的呢?


阅读 382

收藏
2020-04-22

共1个答案

小编典典

承诺不是回调。许诺代表 异步操作未来结果
。当然,以您的方式编写它们,您会获得很少的收益。但是,如果按照使用它们的方式来编写它们,则可以以类似于同步代码的方式编写异步代码,并且更容易遵循:

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

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

但这还不是终点。让我们发现真正的好处:如果您想检查任何步骤中的任何错误怎么办?用回调来做到这一点将是一件令人头疼的事,但是用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
});

几乎与try { ... } catch街区相同。

更好的是:

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调用什么apiapi2api3可以同时运行(例如,如果他们是AJAX调用),但你需要等待三个?没有承诺,您应该必须创建某种计数器。使用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.
});

希望您现在看到一个新的承诺。

2020-04-22