简体   繁体   English

Ajax 异步 - 如何避免 function 在完成请求之前返回

[英]Ajax asynchronous - how to avoid function return before completed request

I have an array of string (id) and I need to iterate on it to make an ajax request to an api and push response in an array.我有一个字符串(id)数组,我需要对其进行迭代以向 api 发出 ajax 请求并在数组中推送响应。 The problem is that, because of asynchronous load, the return statement is made before the end of the call.问题是,由于异步加载,return 语句是在调用结束之前进行的。 Here an example:这里有一个例子:

getArrConcat: function (id) {
    var arr = new Array();
    var arrJoin = "";
    for (var i=0; i<id.length; i++){
        Model.load(id[i], {
            success: function (org) {
                arr.push(org.data);
            }
        });
    }
    arrJoin = arr.join('; ');
    return arrJoin;
}

You can't execute getArrConcat synchronously when the result depends on an ajax request.当结果取决于 ajax 请求时,您无法同步执行getArrConcat

The easiest solution would be to make getArrConcat returning a Promise and make the calling function async .最简单的解决方案是让getArrConcat返回Promise并使调用 function async

This would look more or less like:这看起来或多或少像:

getArrConcat: function (id) {
    return new Promise((resolve) => {
        for (var i=0; i<id.length; i++){
            Model.load(id[i], {
                success: function (org) {
                    var arr = new Array();
                    var arrJoin = "";
                    arr.push(org.data);
                    arrJoin = arr.join('; ');
                    resolve(arrJoin);
                }
            });
        }
    });
},

// call from an async method:
callGetArrConcat: async function() {
    const concatString = await this.getArrConcat(123);
    //Do something with concatString
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM