一般来说,这是个坏主意。让我来告诉你为什么。浏览器中的Javascript基本上是单线程的野兽。想到它,它也是Node.js中的单线程。因此,您在开始等待远程请求成功或失败时不进行任何“返回”操作都可能涉及某种循环,以延迟请求之后的代码执行。像这样:
var semaphore = false;var superimportantInfo = null;// Make a remote request.$http.get('some wonderful URL for a service').then(function (results) { superimportantInfo = results; semaphore = true;});while (!semaphore) { // We're just waiting.}// Code we're trying to avoid running until we know the results of the URL call.console.log('The thing I want for lunch is... " + superimportantInfo);但是,如果您在浏览器中尝试这样做,并且调用花费了很长时间,那么浏览器会认为您的Javascript代码陷入了循环,并在用户的脸上弹出了一条消息,使用户可以停止代码。因此,Javascript的结构如下:
// Make a remote request.$http.get('some wonderful URL for a service').then(function (results) { // Code we're trying to avoid running until we know the results of the URL call. console.log('The thing I want for lunch is... " + results);});// Continue on with other pre which does not need the super important info or // simply end our Javascript altogether. The pre inside the callback will be // executed later.这样的想法是,每当服务调用返回时,便会通过事件触发回调中的代码。因为事件驱动就是Javascript喜欢它的方式。Javascript中的计时器是事件,用户操作是事件,用于发送和接收数据的HTTP
/ HTTPS调用也会生成事件。并且您应该构建代码来响应这些事件。
在远程服务调用返回之前,您是否无法构造代码以使其认为canAccess为假,毕竟它确实是真的?我一直在AngularJS代码中这样做,我不知道我应该向用户显示的最终权限是什么,因为我还没有收到它们,或者我没有收到所有要显示在用户端的数据。首先。我有默认显示,直到真实数据返回,然后页面根据新数据调整为新格式。AngularJS的两种方式绑定使这确实非常容易。



