根据我的理解,有三种方法可以调用异步代码:
request.on("event", callback);fs.open(path, flags, mode, callback);我找到了一个承诺库https://github.com/kriszyp/node-promise,但我没有得到它.
有人可以解释一下什么是承诺,为什么我应该使用它?
另外,为什么它从Node.js中删除了?
我正在阅读这篇文章,关于承诺抽象的部分对我来说似乎有点过于复杂.以下是一个例子:
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);
});
Run Code Online (Sandbox Code Playgroud)
在我看来,以下可以用更少的代码行提供相同的结果:
requestSomeData("http://example.com/foo")
.requestHandler(function(response){
// parse the body
var data = JSON.parse(response.body);
// …Run Code Online (Sandbox Code Playgroud)