Javascript不等待在函数中解析承诺
我的js代码需要等到ajax完成后才能加载数据Javascript不等待在函数中解析承诺,javascript,ajax,promise,Javascript,Ajax,Promise,我的js代码需要等到ajax完成后才能加载数据 if (district_search_value[0] == true) { var zone_search_value = checkZone(district_search_value[1], datas[i]['recipient_zone']); console.log(zone_search_value); } checkZone功能: function checkZone(distric
if (district_search_value[0] == true) {
var zone_search_value = checkZone(district_search_value[1], datas[i]['recipient_zone']);
console.log(zone_search_value);
}
checkZone功能:
function checkZone(district_id, zone_name) {
var value = [];
value[0] = false;
value[1] = 0;
find_zones_from_district_id().then(function(data) {
// Run this when your request was successful
console.log(data);
var zones = JSON.parse(data);
//console.log(zones);
for (zones_row = 0; zones_row < zones.length; zones_row++) {
if (zone_name == zones[zones_row]['zone_name']) {
value[0] = true;
value[1] = zones[zones_row]['id'];
}
}
return value;
}).catch(function(err) {
// Run this when promise was rejected via reject()
console.log(err);
})
}
function find_zones_from_district_id(district_id) {
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: 'ajaxData_for_user.php',
data: {import_excel_find_zones_from_district_id: 'district_id'},
success: function (data) {
resolve(data) // Resolve promise and go to then()
},
error: function (err) {
reject(err) // Reject the promise and go to catch()
}
});
});
}
javascript不等待承诺解决的原因是什么?
在jquery中,我也尝试过$。但这也不会等待ajax加载数据。有两件事需要解决,第三件事是可选的
记录结果之前,请等待承诺得到解决。然后()
find\u zones\u from\u district\u id
function checkZone(district_id, zone_name) {
var value = [];
value[0] = false;
value[1] = 0;
return find_zones_from_district_id().then(function(data) {
// ...
function find_zones_from_district_id(district_id) {
return $.ajax({
type: 'POST',
url: 'ajaxData_for_user.php',
data: {import_excel_find_zones_from_district_id: 'district_id'} // did you want to pass a string here or district_id parameter?
})
}
也许用“等待者”吧?这能回答你的问题吗?Sidenote
$.ajax()
返回一个thenable,它不需要包装在Promise
@STALER中-我尝试使用async wait,但我得到的是Promise{},而不是value@JaredSmith-谢谢你,这很有见地。谢谢你的回答。我已经应用了所有三个更改。现在我从地区id(…)中得到了这个错误。然后(…)。catch不是checkZone函数中的函数。这是代码find\u zones\u from\u district\u id(district\u id)。然后(function(data){
@iamnaez,我认为这是由于jquery Ajax承诺返回了它们自己的承诺。尝试.fail(function(error){})
(请参见)@iamnaez,如果您执行了第三步并直接返回了Ajax调用,请注意Ajax()返回对象,而不是真正的承诺它不会有catch()方法。请改用.fail()
或使用then()
的第二个参数设置错误回调,例如。然后(function(){},function(){/*error callback*/})
function find_zones_from_district_id(district_id) {
return $.ajax({
type: 'POST',
url: 'ajaxData_for_user.php',
data: {import_excel_find_zones_from_district_id: 'district_id'} // did you want to pass a string here or district_id parameter?
})
}