使用promise和defer在angularJS中进行同步和异步调用 [英] synchronous and asynchronous calling in angularJS with promise and defer

查看:65
本文介绍了使用promise和defer在angularJS中进行同步和异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下带有2个服务的服务控制器.在第一响应之前是第二响应.我想做的就像我需要第一响应和第二响应.但我只是坚持使用异步和同步功能,请帮助我解决问题.

I created following controller with 2 service calling with services. Second response comes before then first. i want to do like i need first response first and second response second. but i just stuck with async and sync please help me for solving.

第二个呼叫取决于第一个呼叫.例如,如果第一次调用返回10条记录,那么我必须调用第二次Web服务10次,并从第一次响应中获取ID.所以我用循环,但这是不正确的.

Second call is depends on first call. For example if first call returns 10 record then i have to call second web service 10 time taking id from first response. so i use for loop but it is not proper.

var mycompaigndata = [];

asyncService.loadDataFromUrls($http.get(WSURL + 'api/first/', 
{
    headers: 
    {
        "Authorization":'Bearer <my-token>'
    }
}))
.then(function(data)
{
    console.log(data);
});


asyncService.loadDataFromUrls($http.get(WSURL + 'api/second', 
{
    headers:
    {
        "Authorization":'Bearer <my-token>'
    }
}))
.then(function(data)
{   
    console.log(data);
});

服务

app.service('asyncService', function($http, $q) 
{
    return {
        loadDataFromUrls: function(url) 
        {
            var deferred = $q.defer();
            var urlCalls = [];

            urlCalls.push(url);

            $q.all(urlCalls)
            .then(
            function(results) 
            {
                deferred.resolve(results) 
            },
            function(errors) 
            {
                deferred.reject(errors);
            },
            function(updates) 
            {
                deferred.update(updates);
            });
            return deferred.promise;
        }
    };
});

推荐答案

要确保在第一个调用完成后执行第二个调用,请将第二个调用放在第一个调用的then内.要根据第一次调用的结果数量进行多次第二次"调用,请使用$q.all.

To make sure the second calls are executed after the first one is finished, put the second call within then of the first call. To make multiple 'second' calls depending on the number of results of the first call, use $q.all.

asyncService.loadDataFromUrls('api/first/')
.then(function(firstData) {
    //assuming firstData is an array of 'x' items, do a call for each of these items:
    console.log('results of first call holds ' + firstData.length + ' items');
    var promises = [];
    for(var i = 0; i<firstData.length; i++){
        var id = firstData[i].id;//you can use this to pass to the second call
        promises.push(asyncService.loadDataFromUrls('api/second'));
    }
    return $q.all(promises);
})
.then(function(results) {
  //'results' is an array of results, the nth item holds the result of the 'nth' call to loadDataFromUrls
  for(var i = 0; i<results.length; i++){
    console.log('result nr. ' + i + ' :' + results[i])
  }
});

通过使用return $q.all(promises),您可以避免厄运的承诺金字塔,并保持平坦的结构.

By using return $q.all(promises), you're avoiding the promise pyramid of doom, and keep a flat structure.

您的服务代码不再需要循环.附带说明,您可以缩短服务代码,避免使用显式承诺构造反模式"(请参阅​​

Your service code doesn't need to loop anymore. As a sidenote, you can shorten the code of the service and avoid using the 'explicit promise construction antipattern' (see here) like this:

app.service('asyncService', function($http, $q) 
{
    return {
        loadDataFromUrls: function(url) 
        {
            return $http.get(WSURL + url, {
                headers: {
                  "Authorization": 'Bearer <my-token>'
                }
            }).then(function(response){ return response.data; });
        }
    };
});

这篇关于使用promise和defer在angularJS中进行同步和异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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