简体   繁体   中英

How to use async:false in angular js 1.6, so that java script next line execution get block until $http completed

Currently, I am using angularjs 1.6, calling $http to initialize an array, and using that array after 1000 line of code in an angularjs controller, but some strange thing is happening every time. Sometimes I get array initialized properly and sometimes I don't.

Basically, I would like to call JavaScript code in certain order, like line1, line2, line3 etc, here line1 may call $http , line2 may call some function line3 again $http ,

Even I have tried using

$http( {  method:'POST',
          url:'/getData',
          async:false
        })

But It's not holding execution JavaScript, instead, next line of code gets executed. Is there any way to control this, so that I can execute the JavaScript code in the same order in the same way I have written,

First of all in many case moving to "none asynchrone" call is a bad idea. You don't know how long this call will take, and during this time you block the UI event loop, so nothing more is working and your website will be totaly stuck during this time, which is pretty a bad thing.

Depend of what you are using (ecma script / javascript) but async function seem to be what you are looking for : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/async_function

Exemple :

async function myFunction(){
    var data = await $http.get(...);
    await $http.post(..);
    return "my data";
}

Everything in this function will be execute in the order it's define thanks to the keyword await but it's still asynchrone, the whole function will return a Promise.

myFunction().then(function(myData) {
   console.log("End of the asynchrone function " + myData);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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