gpt4 book ai didi

javascript - ajax 调用内的循环 - 我对事件的顺序感到困惑

转载 作者:行者123 更新时间:2023-12-01 05:46:29 24 4
gpt4 key购买 nike

我觉得我没有完全理解ajax调用是如何工作的(我保证我试图理解,但尽管我认为我理解,但我的代码没有按预期工作)。这就是我想做的:我有服务器端代码,它只返回图像 url 数组。对于每张图像,我都使用客户端面部检测库进行面部检测。对所有图像进行面部检测后,我需要在 Canvas 上将它们一一绘制(这不再真正相关)。现实中发生的情况是,我首先收到“已完成寻找面孔”的警报,然后我才收到带有图像 url 的警报,并且它对所有图像使用相同的 url。我还将“async”设置为 false,因为我认为这将使事件的顺序按我的预期工作。如果我不清楚,请告诉我,提前非常感谢!

//Call FB api from server side script
function callApi(userId, token) {
$.ajax({
"type": "GET",
"url": API_ROUTE + "?userid=" + userId + "&token=" + token,
"async": false, //setting to false because we don't want to start drawing before face detection is done
success: function(data, status, xhr) {
face_coords = []; //Array that stores face locations for each image (indexs are respective to
//image indexes in aImages)
for (var i = 0; i < data.length; i++) {
var img_url = data[i];
img_url.replace('https://', 'http://'); //To avoid cross-domain issues

// collect all images
var oImg = new Image();
oImg.crossOrigin = 'Anonymous';
oImg.src = img_url;
aImages.push(oImg);
$("#myPicture").attr("src", oImg.src).load(function() {
var coords = $('#myPicture').faceDetection();
//find the face detected with the highest confidence
if (coords.length > 0) {
var highest_confidence = 0,
highest_c = 0;
for (var c = 0; c < coords.length; c++) {
if (coords[c].confidence > highest_confidence) {
highest_confidence = coords[c].confidence;
highest_c = c;
}
}
}
face_coords.push(coords[highest_c]);
alert ("done with " + $('#myPicture').get(0).src)
});
}
}
});
alert("done with looking for faces");
var canvas = $('#myCanvas').get(0);
context = canvas.getContext('2d');
//draw first image
context.drawImage(aImages[0], 0, 0, CANVAS_WIDTH, aImages[0].height / aImages[0].width * CANVAS_WIDTH);
changeSlide(); //call on the first image in order to not waste 5 seconds
timer = setInterval(changeSlide, 5000); // set inner timer
}

最佳答案

你可以尝试 .done() 而不是成功。

function getData() {
return $.ajax({
url : 'example.com',
type: 'GET'
});
}

function handleData(data /* , textStatus, jqXHR */ ) {
alert(data);
//do some stuff
}

getData().done(handleData);

关于javascript - ajax 调用内的循环 - 我对事件的顺序感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26324340/

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