相关疑难解决方法(0)

了解node.js中的promise

根据我的理解,有三种方法可以调用异步代码:

  1. 事件:例如. request.on("event", callback);
  2. 回调:例如. fs.open(path, flags, mode, callback);
  3. 承诺

我找到了一个承诺库https://github.com/kriszyp/node-promise,但我没有得到它.

有人可以解释一下什么是承诺,为什么我应该使用它?

另外,为什么它从Node.js中删除了?

javascript node.js promise

146
推荐指数
6
解决办法
10万
查看次数

CommonJS中"承诺"抽象的好处是什么?

我正在阅读这篇文章,关于承诺抽象的部分对我来说似乎有点过于复杂.以下是一个例子:

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)

javascript abstraction commonjs promise

13
推荐指数
1
解决办法
6133
查看次数

标签 统计

javascript ×2

promise ×2

abstraction ×1

commonjs ×1

node.js ×1