首页 > 解决方案 > 这两种处理顺序 Promise 的风格有什么区别

问题描述

当我们想按顺序依次执行几个 then 函数时,这两种风格有什么区别:

1-使用嵌套的thens

$http.get('api').then(function(){
    processBlocks(obj.data).then(function(){
        alert('it is done')
    });
});

2- 展平嵌套的 then

$http.get('api').then(function(){
    return processBlocks(obj.data);
}).then(function(){
    alert('it is done')
});

很明显,第二个更具可读性,但也有性能差异吗?

标签: javascriptpromise

解决方案


$http.get('api').then(function(){
    processBlocks(obj.data).then(function(){
        alert('it is done')
    });
});

在这种情况下,如果您then像这样连接另一个:

$http.get('api').then(function(){
    processBlocks(obj.data).then(function(){
        alert('it is done')
    });
}).then(function(){
alert('it is done')
});

如果processBlocks()抛出异常,没关系,下一个promise会被触发,但是:

$http.get('api').then(function(){
    return processBlocks(obj.data);
}).then(function(){
    alert('it is done')
});

在这种情况下,如果第一个then失败,则取消序列,如果有catch块,它将被触发


推荐阅读