【问题标题】:Ajax response late return data, but function is already execute and return data without ajax dataAjax响应延迟返回数据,但函数已经执行并返回没有ajax数据的数据
【发布时间】: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


    【解决方案1】:

    我在这里找到了答案

     async function getProducts(product_links, product_quantity, trigger_word){
            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())
                            });
                        }else{
                            var product_json = `${$(product_links[i]).val()}.json`;
                            let index = i;
    
                            await $.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
                                    });
                                },
                                error:function(err) {
                                    throw new Error("Something went wrong, please check your internet connection and disable your adblocker, 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!");
            }
    
            return obj;
        }
    
    getProducts(product_links, product_quantity, trigger_word)
                .then(function (products) {
                    console.log(products);
                })
                .catch(function (err){
                    console.log(err);
                });
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2014-06-28
    • 2016-07-28
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多