gpt4 book ai didi

javascript - 这两种处理顺序 promise 的风格有什么区别

转载 作者:行者123 更新时间:2023-11-29 10:02:57 24 4
gpt4 key购买 nike

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

1- 使用嵌套 thens

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

2- 压平嵌套的thens

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

很明显,第二个可读性更好,但是否也存在性能差异?

最佳答案

$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 block ,它将被触发

关于javascript - 这两种处理顺序 promise 的风格有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51299626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com