Angularjs processes a summary of multiple asynchronous request methods, and angularjs Asynchronously

Source: Internet
Author: User

Angularjs processes a summary of multiple asynchronous request methods, and angularjs Asynchronously

In actual business, you often need to wait for several requests to complete before proceeding to the next step. However, $ http in angularjs does not support synchronous requests.

Solution 1:

Copy codeThe Code is as follows:
$ Http. get ('url1'). success (function (d1 ){
$ Http. get ('url2 '). success (function (d2 ){
// Processing logic
});
});

Solution 2:

The methods in then are executed in sequence.

Copy codeThe Code is as follows:
Var app = angular. module ('app', []);
App. controller ('promiscontrol', function ($ scope, $ q, $ http ){
Function getJson (url ){
Var deferred = $ q. defer ();
$ Http. get (url)
. Success (function (d ){
D = parseInt (d );
Console. log (d );
Deferred. resolve (d );
});
Return deferred. promise;
}

GetJson('json1.txt '). then (function (){
Return getJson('json2.txt ');
}). Then (function (){
Return getJson('json1.txt ');
}). Then (function (){
Return getJson('json2.txt ');
}). Then (function (d ){
Console. log ('end ');
});
});

Solution 3:

$ Q. all the first parameter of the method can be an array (object ). After all the content in the first parameter is executed, the then method is executed. All return values of the method of the first parameter are passed in the form of an array (object.

Copy codeThe Code is as follows:
Var app = angular. module ('app', []);
App. controller ('promiscontrol', function ($ scope, $ q, $ http ){
$ Q. all ({first: javashttp.get('json1.txt '), second: javashttp.get('json2.txt')}). then (function (arr ){
Console. log (arr );
Angular. forEach (arr, function (d ){
Console. log (d );
Console. log (d. data );
})
});
});

$ Q detailed usage there are many tutorials online. I just got in touch with it. It's hard to say anything about it. The above code is written according to my understanding. After testing, there is no problem.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.