简体   繁体   English

使用AngularJS Promise

[英]Using AngularJS Promise

I am currently attempting to learn the AngularJS framework and I keep hearing about something called "promise". 我目前正在尝试学习AngularJS框架,并且不断听到有关“承诺”的信息。 I have researched a little about it, although I cannot seem to find a thorough explanation to how and when to use "promises". 我已经对此进行了一些研究,尽管我似乎无法找到有关如何以及何时使用“承诺”的详尽解释。

Can anyone please explain and provide a solution between using a promise, and not using a promise. 任何人都可以在使用承诺与不使用承诺之间进行解释并提供解决方案。 What is the advantage of using a promise over not using one? 与不使用承诺相比,使用承诺有什么好处?

All answer are appreciated. 所有的答案表示赞赏。

Thanks. 谢谢。

promises implementation basically provides an interface which define at least one method 'when' that return therefore, a "Promise", thus a result from an async operation. Promise实现基本上提供了一个接口,该接口定义了至少一个“何时”返回的方法(因此返回)“ Promise”,即异步操作的结果。

Advantages are better code readability (and production as well), better reuse of the results without incurring on the scaring "callbacks hell", chainabilty, etc... 优点是更好的代码可读性(以及生产),结果的更好重用,而不会引起可怕的“回调地狱”,可链接性等。

A simple scenario with jQuery: jQuery的简单方案:

without promises 没有承诺

$.ajax({
    url: someurl,
    success: function(data)
    {
        //do something with data
    }
});

with promises 承诺

var p = $.ajax({ url: someurl });

$.when(p).then(function(data)
{
    //do something with data    
});

However, a better explanation: http://wiki.commonjs.org/wiki/Promises/A 但是,更好的解释是: http : //wiki.commonjs.org/wiki/Promises/A

The official documentation says that 官方文件说

The promise api allows for composition that is very hard to do with the traditional callback (CPS ) approach. promise api允许使用传统的回调(CPS)方法很难实现的合成。 For more on this please see the Q documentation especially the section on serial or parallel joining of promises. 有关更多信息,请参阅Q文档,尤其是有关Promise串行或并行连接的部分。

http://docs.angularjs.org/api/ng/service/$q http://docs.angularjs.org/api/ng/service/$q

I think the easiest explanation could be that it's a much better and cleaner way to do a serial or very complex callbacks than the traditional way. 我认为最简单的解释可能是,与传统方法相比,它是执行串行或非常复杂的回调的更好,更干净的方法。

This is the link you can read more about the benefit of using promise: 这是您可以阅读更多有关使用promise的好处的链接:

promises specification 承诺规范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM