我有一个像这样的for循环:
var currentLargest
for (var site in sites) {
// Each site is a website (www.mysite1.com, www.mysite2.com, etc.)
$.getJSON(site).then(function(data) {
if (data > currentLargest) {
currentLargest = data
}
});
}
// Here is where I want to use "currentLargest"
它会检查多个不同的网站以获得最大价值。但是,我无法在for循环之后提取 后需要的数据。我只能在promise中与currentLargest
进行交互,但该数据仅与其中一个站点相关(直到for循环后才完成所有站点的循环)。
如何在包含currentLargest
承诺的for循环后访问getJSON
值?
答案 0 :(得分:1)
// Your code:
/*
var currentLargest
for (var site in sites) {
// Each site is a website (www.mysite1.com, www.mysite2.com, etc.)
$.getJSON(site).then(function(data) {
if (data > currentLargest) {
currentLargest = data
}
});
}
*/
// Updated:
const sitePromisesArr = sites.map((site) => $.getJSON(site));
$.when(sitePromisesArr)
.then((valArr, index) => {
// The "valArr" here will be an Array with the responses
const largest = valArr.reduce((current, next) => next > current ? next : current, 0);
// This will be the largest value.
console.log(largest);
// This will be the site that contains the largest value.
console.log(sitePromisesArr[index]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:-1)
您需要使用异步循环,然后在完成所有异步getJSON请求后执行回调。您可以使用http://caolan.github.io/async/docs.html#each来帮助解决此问题。