javascript - AngularJs:让方法在内部调用 $http 或 $resource 时同步返回

标签 javascript angularjs

有没有办法等待一个 promise ,以便您可以从中获得实际结果并返回它而不是返回 promise 本身?我正在考虑类似于 C# await 关键字如何与任务一起使用的东西。

这是一个示例,说明为什么我想要一个像 canAccess() 这样的方法,它返回 true 或 false 而不是 promise,以便可以在 if 语句中使用它。方法 canAccess() 将使用 $http 或 $resource 进行 AJAX 调用,然后以某种方式等待 promise 得到解决。

看起来像这样:

$scope.canAccess = function(page) {
    var resource = $resource('/api/access/:page');
    var result = resource.get({page: page});

    // how to await this and not return the promise but the real value
    return result.canAccess;
}

有没有办法做到这一点?

最佳答案

一般来说,这是一个坏主意。让我来告诉你为什么。浏览器中的 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 code which does not need the super important info or 
// simply end our JavaScript altogether. The code inside the callback will be 
// executed later.

这个想法是回调中的代码将在服务调用返回时由事件触发。因为事件驱动是 JavaScript 喜欢的方式。 JavaScript 中的计时器是事件,用户操作是事件,发送和接收数据的 HTTP/HTTPS 调用也会生成事件。并且您应该构建您的代码以在这些事件发生时对其作出响应。

你能不能构造你的代码,让它认为 canAccess 是假的,直到远程服务调用返回并且它可能最终发现它真的是真的?我一直在 AngularJS 代码中这样做,我不知道我应该向用户显示的最终权限集是什么,因为我还没有收到它们,或者我还没有收到要显示在第一页。我有默认显示,直到真实数据返回,然后页面根据新数据调整为新形式。 AngularJS 的双向绑定(bind)使这非常容易。

关于javascript - AngularJs:让方法在内部调用 $http 或 $resource 时同步返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184070/

相关文章:

javascript - AngularJS - 如何将纯 JavaScript 插件转换为 Angular 指令(?)

html - angularjs 中的登录服务实现不起作用

javascript - jVectorMap 中的滚动控件

javascript - Node.js - 加密

javascript - React Native + Redux 基本身份验证

javascript - javascript匿名函数的生命周期是多少?

javascript - Sequelize : How to get record with createdat greater than 1 hour

javascript - Angularjs:想要在其各自的 "1st date"单元格上启动 "weekday"

javascript - 我无法使用 jQuery 更改工具提示 Bootstrap 位置

javascript - 为什么有些 Angular $scope 功能 "return"操作?