CommonJS中“承诺”抽象的好处是什么? [英] What is the benefit of a 'promise' abstraction in CommonJS?

查看:138
本文介绍了CommonJS中“承诺”抽象的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading this article and the section on the promise abstraction seems a little overly complicated to me. The following is given as an example:

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);
    });

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

It seems to me that the following could provide the same result with fewer lines of code:

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(...)结果是一个非常昂贵的操作会发生什么;你必须挂起,直到一切都结束,这可能并不总是你想要的。

While it is true that both will ultimately accomplish the same thing, the difference is that your second example is not asynchronous. For example, consider what happens if JSON.parse(...) turns out to be an extremely expensive operation; you'll have to hang until everything's finished, which may not always be what you want.

这就是承诺给你的东西:推迟计算权利的强大能力回答直到更方便的时间。顾名思义,构造承诺在某个时刻给你结果,但不一定就是现在。您可以阅读更多关于期货和承诺的更多信息 此处

That's what promises get you: the powerful ability to defer the computation of the right answer until a more convenient time. As the name suggests, the construct "promises" to give you the result at some point, just not necessarily right now. You can read more about futures and promises work on a larger scale here.

这篇关于CommonJS中“承诺”抽象的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆