从承诺中获取数据而不是返回承诺 [英] Get data out of a promise instead of returning a promise

查看:78
本文介绍了从承诺中获取数据而不是返回承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉,如果其他承诺线程已经回答了这个问题,但在查看其中一些时,我只是没有得到解决问题的答案。我有三个json文件,我想抓取,解析和手动合并。问题是我陷入了承诺监狱。让我向您展示我的angularjs控制器中的一些代码。

I am so sorry if the other promise threads have answered this but when looking at some of them I am just not getting the answer to solve my issue. I have three json files that I want to grab, parse and manually merge. The problem is I am getting stuck in promise jail. Let me show you some of the code from my angularjs controller.

$scope.tests = [];

$scope.tests = $http.get('results/testResults.json').then(function(res) {
  return res;
});

console.dir($scope.tests);

从console.dir我得到了一个承诺,但我希望的是来自的数据res变量。必须有一些方法来获取数据。有没有办法从全局变量的承诺中获取数据,因此其他函数承诺可以使用这些数据?谢谢

From the console.dir I am getting a promise but what I was hoping for was the data from the res variable. There has to be some way to get that data out. Is there no way to get that data out of the promise to a global variable so other promises of functions can use this data? Thanks

推荐答案

这个承诺将来会有一段时间完成。在数据在promise中之前,您正在检查promise变量。您应该留在承诺链中以使用您的数据。在承诺链之外,你不知道异步事件的时间(这就是你首先使用promises的原因)。

The promise completes some time in the future. You are examining the promise variable before the data is in the promise. You should stay in the promise chain to use your data. Outside the promise chain, you don't know the timing of the asynchronous events (that's why you use promises in the first place).

如果你真的不想要在第一个 .then()处理程序中使用数据,这是使用它的理想位置,然后你可以链接另一个 .then() 兑换承诺:

If you really don't want to use the data right in your first .then() handler which is the ideal place to use it, then you can chain another .then() onto your promise:

$scope.tests = $http.get('results/testResults.json');

$scope.tests.then(function(data) {
   // can use data here
});

仅供参考,承诺不会将数据填充到全局变量中。当调用这些回调时,它们使数据可用于 .then()回调。

FYI, promises do not populate data into global variables. They make the data available to use in .then() callbacks when those callbacks are called.

这篇关于从承诺中获取数据而不是返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆