【发布时间】:2011-01-10 17:35:18
【问题描述】:
我正在阅读this article,关于承诺抽象的部分对我来说似乎有点过于复杂。下面举例说明:
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);
});
【问题讨论】:
-
你是对的,使用 Promise 进行同步操作是没有意义的。所以结果应该是相等的。但这是一个示例,并说明了 Promise 的用法。对于在您的示例之后运行的代码,确实存在差异。如果您需要在示例之后运行某些东西,那么您可以在不知道示例代码在做什么的情况下(通过使用 promise 方法)执行它
标签: javascript abstraction commonjs promise