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

标签 javascript abstraction commonjs promise

我正在阅读 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/

相关文章:

javascript - 逐字节读取文件并解析为 int

javascript - 谷歌地图上的固定标记

java - Java 解释器中数学运算的抽象

javascript - ES2015 `import` 替代 `require()()` ?

javascript - 如何使用 React 实现滚动 spy

c# - 如何防止泄漏抽象?

c# - 我应该如何将我的商业模式与我的观点联系起来?

module - Typescript 模块创建 AMD vs Common JS

javascript - 客户端模块工作流程 : (Browserify + npm + gulp) or (RequireJS + Bower + gulp)?

javascript - 带有 setTimeout 的嵌套 Promise