AngularJS:如何用角承诺工作 [英] AngularJS : How to work with Angular Promises

查看:209
本文介绍了AngularJS:如何用角承诺工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,使一个休息服务电话,我婉使用从返回的数据来填充一个数组。
角回报承诺,我不知道如何与数据无极工作来填充数组。

I have a function that makes a rest service call that I wan to use to populate an array from the data returned. Angular returns a Promise, and I do not know how to work with the data in the Promise to populate an array.

我的功能:

    $scope.save= function(){

    var duplicateNames= [];
    for(var i=0; i < ids.length; i++){
        var id= "bns-" + i;
        var aName= document.getElementById(id).value;
        var responsePromise= $http.get("/rest/v1/names/" + aName + "/");
        responsePromise.success(function(data, status, headers, config) {
            if(data.name.length > 0)
                duplicateNames.push(data.name);
        });
    }
    console.log(duplicateNames);

剩下的调用返回的数据,如果aName的存在,那么,我要跟踪它的数组中为止。
我如何暂停的执行,使阵列duplicateNames将有aName添加到它?

The rest call returns data if "aName" exists, then I want to keep track of it in the array. How do I "pause" execution so that the array "duplicateNames" will have "aName" added to it?

推荐答案

您不能暂停执行的,承诺的全部意义就在于它异步执行。也就是说你的code继续正在处理HTTP请求来执行。一旦HTTP请求返回了结果,你的成功函数被调用。在这个例子中,你所提供的的console.log 语句 responsePromise.success 函数之前执行。如果您移动日志语句转换成成功的功能,你会看到预期的结果。

You can't pause execution, the whole point of a promise is that it executes asynchronously. That is to say your code continues to execute while the http request is being processed. Once the http request has returned a result, your success function is called. In the example you provided the console.log statement executes before the responsePromise.success function. If you move the log statement into the success function, you will see the expected results.

在您的例子中, duplicatNames 数组不是当前$范围的模型,所以它的价值有限,因为你已经发现 - 数组中的价值当函数退出是不是你感兴趣的值。然而,如果你使数组模型通过其连接到控制器的 $范围,可以使用2 - 双向绑定或 $观看语句做更新的价值的东西。

In your example, the duplicatNames array is not a model of the current $scope, so it's of limited value, as you've discovered - the value of the array when the function exits is not the value you are interested in. If, however, you make the array a model by attaching it to the controller's $scope, you can use 2-way binding or a $watch statement to do something with the updated value.

基本上你需要开始思考异步,并了解对HTTP请求的另一端过程可能需要一些时间,你需要考虑它。有吨资源对学习角承诺这里有4个:

Basically you need to start thinking asynchronously, and understand that processes on the other end of an HTTP request may take time which you need to account for it. There are tons of resources on learning about angular promises here are 4:

  • https://docs.angularjs.org/api/ng/service/$q
  • Promises in AngularJS and where to use them?
  • http://lostechies.com/gabrielschenker/2014/02/04/angularjspart-11-promises/
  • http://liamkaufman.com/blog/2013/09/09/using-angularjs-promises/

这篇关于AngularJS:如何用角承诺工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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