gpt4 book ai didi

javascript - CommonJS 中的 'promise' 抽象有什么好处?

转载 作者:可可西里 更新时间:2023-11-01 01:49:54 26 4
gpt4 key购买 nike

我正在阅读 this article关于 promise 抽象的部分对我来说似乎有点过于复杂。举例如下:

requestSomeData("http://example.com/foo") // returns a promise for the response
.then(function(response){ // ‘then’ is used to provide a promise handler
return JSON.parse(response.body); // parse the body
}) // returns a promise for the parsed body
.then(function(data){
return data.price; // get the price
}) // returns a promise for the price
.then(function(price){ // print out the price when it is fulfilled
print("The price is " + price);
});

在我看来,以下代码可以用更少的代码行提供相同的结果:

requestSomeData("http://example.com/foo")
.requestHandler(function(response){
// parse the body
var data = JSON.parse(response.body);

// get the price
var price = data.price;

// print out the price
print("The price is " + price);
});

最佳答案

虽然两者确实最终会完成同一件事,但不同之处在于您的第二个示例不是异步的。例如,考虑如果 JSON.parse(...) 结果是一个极其昂贵的操作会发生什么;您必须挂起直到一切都完成,这可能并不总是您想要的。

这就是 promises 带给您的好处:将正确答案的计算推迟到更方便的时间的强大能力。顾名思义,该结构“ promise ”在某个时候给您结果,但不一定是现在。您可以阅读更多关于更大规模的 future 和 promise 工作 here .

关于javascript - CommonJS 中的 'promise' 抽象有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2160100/

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