简体   繁体   English

如何在angular js 1.6中使用async:false,以便Java脚本下一行执行得到阻塞,直到$ http完成

[英]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. 当前,我正在使用angularjs 1.6,调用$http初始化一个数组,并在angularjs控制器中经过1000行代码后使用该数组,但是每次都会发生一些奇怪的事情。 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 , 基本上,我想按一定顺序调用JavaScript代码,例如line1,line2,line3等,在这里line1可以调用$http ,line2可以再次调用某些函数line3 $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. 但是它不保存执行JavaScript,而是执行下一行代码。 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, 有什么方法可以控制它,以便我可以以与编写脚本相同的顺序执行JavaScript代码,

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. 您不知道此调用将花费多长时间,并且在此期间,您阻止了UI事件循环,因此没有任何作用,并且您的网站在此期间将完全卡住,这是一件坏事。

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 取决于您使用的内容(ecma脚本/ javascript),但是异步功能似乎正是您要寻找的: 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. 由于使用关键字await ,该函数中的所有内容将按照其定义的顺序执行,但仍处于异步状态,整个函数将返回Promise。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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