gpt4 book ai didi

javascript - Deferred、Promise 和 Ajax 的顺序不正确

转载 作者:行者123 更新时间:2023-12-03 11:02:50 25 4
gpt4 key购买 nike

我正在尝试设置一个 Ajax 调用循环和一个在所有 Ajax 调用解决后运行的函数。我读了一堆关于这个问题的问题,并认为我能够将它应用到我的代码中,但它不起作用,我一生都无法弄清楚为什么。

这是 JS 代码。 map 函数 运行了 10 次(仅供引用)。

function addData(data) {
var deferreds = [];
$.map(data, function(job) {
deferreds.push(addLocation(job));
});

console.log(deferreds);
$.when.apply($, deferreds).then(mapData(data));
}

function addLocation(job) {
var dfd = $.Deferred(),
url = url;

console.log('in the addLocation function, outside the ajax call');
$.ajax({
url: url,
dataType: 'jsonp',
jsonp: 'json_callback'
}).done(function(location) {
job.lnglat = [parseFloat(location[0].lon), parseFloat(location[0].lat)];
console.log('resolved location');
dfd.resolve();
});

return dfd.promise();
}

function mapData(data) {
console.log('in the mapData function');
console.log(data);
var point = svg.selectAll('points')
.data(data);

point.exit().remove();
point.enter().append('circle')
.attr('r', 2.5);

point
.attr('cx', function(d) {
console.log(d); //shows d and has the lnglat but I think that is due to the developer tools reading the final result, not the result at the time
console.log(d.lnglat); // this gives undefined
console.log(d.lnglat[0]); // this gives an error as it hasn't been defined
console.log(projection(d.lnglat[0]));
return projection(d.lnglat[0])[0];
})
.attr('cy', function(d) {
return projection(d.lnglat[1])[1];
});
}

Chrome 开发者工具报告以下顺序:

in the addLocation function, outside the ajax call  //x10
[Object, object...] //this is the object list of deferred objects, there are 10 of them
in the mapData function
[Object, object..] //this is the object list of data from the mapData function
Object > ... //this is the d object in the mapData function > point anonymous function
undefined // this is the result of d.lnglat
Uncaught typeError ... // this is the result of d.lnglat[0] which doesn't exist yet
resolvedLocation //x10 this should be a lot higher right?

所以我希望 resolvedLocation console.logmapData 函数 运行之前运行,我以为我已经这样设置了,但显然不工作。我错过了什么?

最佳答案

正如adeneo在评论中所说,这里的问题是在

中对mapData的立即调用

$.when.apply($, deferreds).then(mapData(data))

要解决这个问题,您需要使用绑定(bind)来保持大部分解决方案完好无损(并且不要对其进行太多更改)。这应该有效:

$.when.apply($, deferreds).then(mapData.bind(this, data))

绑定(bind)不会延迟函数的调用。它将数据参数绑定(bind)到函数的调用,因此当“then”函数调用mapData时,它会使用“data”作为其参数,并且只有在所有 promise 都得到解决之后才会发生。

关于javascript - Deferred、Promise 和 Ajax 的顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28003664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com