从承诺中获取数据而不是返回承诺

编程入门 行业动态 更新时间:2024-10-24 08:24:36
本文介绍了从承诺中获取数据而不是返回承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我很抱歉,如果其他承诺线程已经回答了这个问题,但在查看其中一些时,我只是没有得到解决问题的答案。我有三个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.

更多推荐

从承诺中获取数据而不是返回承诺

本文发布于:2023-10-25 08:11:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!