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

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

问题描述

我正在阅读 这篇文章和关于promise抽象的部分对我来说似乎有点过于复杂.以以下为例:

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.

这就是 Promise 带给您的:强大的能力,可以将正确答案的计算推迟到更方便的时间.顾名思义,该构造承诺"在某个时候为您提供结果,只是不一定是现在.您可以在此处阅读更多关于期货和承诺工作的更多信息.

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天全站免登陆