gpt4 book ai didi

javascript - promise 不只是回调吗?

转载 作者:IT老高 更新时间:2023-10-28 11:02:19 26 4
gpt4 key购买 nike

我已经开发 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
});
});
});

哪个代码更多,可读性更低。我在这里没有任何收获,它也不是突然神奇地“平坦”。更不用说必须将事情转换为 promise 。

那么,这里的 promise 有什么大惊小怪的?

最佳答案

Promise 不是回调。 promise 代表异步操作的 future 结果。当然,按照你的方式编写它们,你得到的好处很少。但是如果你按照它们的用途来编写它们,你可以用一种类似于同步代码的方式来编写异步代码,并且更容易理解:

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

希望你现在以全新的眼光看待 Promise。

关于javascript - promise 不只是回调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22539815/

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