How do I return the response from an asynchronous call?
并没有帮助我,可能会使Googlers感到困惑,因为
它的状态是什么在工作,而不是在工作。女巫是the_data_you_want
=响应,这实际上是答案。
我正在使用Ajax,Jquery,Promise和PHP的项目中工作。
我用函数填充数组。
var data = validateInput2(field_id, data_type, value).then(function (response) {
console.log("Succès !", response); <-----------------------------
data = response; Scope where data is filled
alert('R : '+data); <-----------------------------
}, function (error) {
console.error("Échec !", error);
});
alert('DATA : '+data); <---------------------------
if (data[0] == 'true') { Outside the scope where data
$(container[1]).addClass("pass_f"); is a pending promise object
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
else {
$(container[1]).removeClass("pass_f");
$(container[1]).addClass("err_f");
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
现在,如果您看一下警报语句,第一个
alert('R : '+data);
将告诉我我应该看到的内容。从PHP返回的数组。由于
console.log("Succès !", response);
,我可以在控制台中看到相同的好值,但是当我继续前进并转到页面应更新的部分时。女巫是alert('DATA : '+data);
数据不再是原来的数据。相反,我在警报框中得到了[object Object]
。在控制台中承诺{[[[PromiseStatus]]:“待定”,[[PromiseValue]]:未定义}
似乎结果中包含的数组仅在内部;
{
console.log("Succès !", response);
data = response;
alert('R : '+data);
}
所以我知道Promise正在工作,因为我的页面正在等待状态为待定的对象,并且我不再遇到数据未定义的错误。
最佳答案
var data = validateInput2(field_id, data_type, value).then(function (response) {
console.log("Succès !", response);
data = response;
if (data[0] == 'true') {
$(container[1]).addClass("pass_f");
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
else {
$(container[1]).removeClass("pass_f");
$(container[1]).addClass("err_f");
$(container[1]).html(data[2]);
$(container[0]).html(data[1]);
}
}, function (error) {
console.error("Échec !", error);
});
alert('DATA : '+data);
这是因为您正在使用数据,并且那一刻的数据是有希望的,所以要这样做