【发布时间】:2021-12-29 17:02:14
【问题描述】:
我的代码有问题,我需要从函数返回对象数组,但如果我传递的某些 url 有我需要的数据,我有条件,然后我填充数组并用 promise 返回它,但如果某些 url 没有没有我需要的数组所需的数据我向 url 发送 ajax 请求以获取该数据并填充数组并返回它。问题是,当我的 url 包含我需要传递的数据并且 url 没有我需要传递的数据时,我的数组只返回了我需要的 url 中具有该数据的数据对象。如何在 url 中等待不需要数据的数据,然后返回数组这里是代码。返回的数组的长度与传递的url有数据并且没有我需要的数据是1。没有等待ajax数据被推入数组。
function getProducts(product_links, product_quantity, trigger_word){
return new Promise(function(resolve, reject) {
var obj = [];
// Checking if values are equal and not empty //
if((product_links.length > 0 && product_quantity.length > 0) && (product_links.length == product_quantity.length)){
// Looping through products and getting their variant id and quantity values //
for (var i = 0; i < product_links.length; i++){
// Checking if product link as enterd value are not empty, that the same we check for product quantity //
if($(product_links[i]).val() != '' && $(product_quantity[i]).val() != '' && isUrl($(product_links[i]).val()) && $.isNumeric($(product_quantity[i]).val()) && $(product_quantity[i]).val() > 0){
// We find all products that have a variant in their link and push them to array with their quantity //
var url = new URL($(product_links[i]).val());
var search_params = url.searchParams;
if(search_params.has("variant")){
obj.push({
id: parseInt(search_params.get("variant")),
quantity: parseInt($(product_quantity[i]).val())
});
console.log("Product with variant: ", obj);
resolve(obj);
}else{
var product_json = `${$(product_links[i]).val()}.json`;
let index = i;
$.ajax({
crossDomain: true,
type: "GET",
contentType: "application/json; charset=utf-8",
url: product_json,
dataType: "jsonp",
headers:{
"Access-Control-Allow-Origin": "*"
},
success: function(res){
var first_variant_id = res['product']['variants'][0]['id'];
var product_name = res['product']['title'];
var quantity_value = parseInt($(product_quantity[index]).val());
obj.push({
id: first_variant_id,
quantity: quantity_value
});
resolve(obj);
console.log("Product name: ", product_name , "Product id: ", first_variant_id, "Quantity: ", quantity_value);
},
error:function(err) {
throw new Error("Something went wrong, please check your internet connection and try again later!");
}
});
}
}else{
throw new Error("Something went wrong, please check all product link fields and their quantity!");
}
}
}else{
throw new Error("Something went wrong, please check all product link fields and their quantity!");
}
if(trigger_word == ''){
throw new Error("Something went wrong, please check trigger word enterd field!");
}
});
}
getProducts(product_links, product_quantity, trigger_word)
.then(function (products) {
console.log(products);
console.log(products.length);
products.forEach(function(variant){
console.log(variant);
});
})
.catch(function (err){
console.log(err);
});
【问题讨论】:
标签: javascript jquery ajax promise