2 $ http获取功能 [英] 2 $http get function

查看:68
本文介绍了2 $ http获取功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出2个JSON url,如何确保代码已完成从a.json检索数据,然后仅开始从b.json检索数据,然后仅运行init函数?

Given 2 JSON url, how do I make sure the code has finished retrieving the data from a.json, then only start retrieving the data from b.json, then only run init function?

var aUrl = "a.json";
var bUrl = "b.json"; 

我的尝试:

var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) { 
  $http.get(aUrl).success(function(data) {   }); 
  $http.get(bUrl).success(function(data) {  
   init()}
);
var init = function(){}

推荐答案

I faced the same issue in my initial days.
There are many ways of doing it exactly as suggested here.
You need to know below two things before exploring:

1. JavaScript是同步的

Synchronous Example[Flow in sequence]:
       console.log('1')
       console.log('2')
       console.log('3')

它记录1 2 3.

It logs 1 2 3.

拨打服务电话的示例

   1. $http.get(aUrl).success(function(data) {  console.log('1.any time response returns')  });  
   2. $http.get(bUrl).success(function(data) { console.log('2.mummy returns')};

因此,单线程javascript首先会使用$ http.get(aUrl)调用您的以下代码,该代码会访问url并进行处理以从后台获取数据.

So as single-threaded javascript will first make a call to your below code with $http.get(aUrl) which hits the url and processes to fetch the data from the background.

  1. $ http.get(aUrl).success(function(data){console.log('1.any time response return')});

但是这里要注意的关键是上面请求的$ http.get(aUrl)不会等到成功/错误返回数据.它移至下一个请求$ http.get(bUrl),我们只是无法预测哪个响应会更早出现.

But the key thing to notice here is $http.get(aUrl) requested above doesn't wait until the data is returned in success/error. It moves to the next request $http.get(bUrl) and we just can't predict which response comes earlier.

  1. $ http.get(bUrl).success(function(data){console.log('2.mummy返回')}

输出可能是

1.任何时间响应都返回

1.any time response returns

2.mummy返回

                     or

2.mummy返回

2.mummy returns

1.任何时间响应都返回

1.any time response returns

因此,为了克服这种情况,我们以各种方式遵循异步操作.

So, to overcome this situation we follow asynchronous operations in various ways.

2.异步呼叫

$http.get(aUrl)
    .then(function(response){
      console.log('inside the first then response');
      console.log(response.data);

      //executing the second request after we get the first request
     //and returns the **outputResponse** which is captured in the next **then** block
      return $http.get(bUrl);
    })
    .then(function(**outputResponse** ){
      console.log('outputResponse generated from to the second bUrl');
      //you can call init() here 
    });

上面的代码足以满足您的要求.

Above code suffices your requirement.

在将来使用$ q单击以获取更多信息

单击此处以了解为什么要改用成功的秘诀.

这篇关于2 $ http获取功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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