0

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. The problem is that, because of asynchronous load, the return statement is made before the end of the call. 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;
}
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Nov 19 '19 at 10:47

1 Answers1

1

You can't execute getArrConcat synchronously when the result depends on an ajax request.

The easiest solution would be to make getArrConcat returning a Promise and make the calling 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
}
Jonas Osburg
  • 1,733
  • 1
  • 14
  • 17
  • can I use async function in extjs? – Cristina Moretti Nov 19 '19 at 11:26
  • Generally yes. During development you need a browser that supports async functions (all recent browsers do). A recent Sencha CMD Version is able to transpile Promises and async functions to support older browsers as well (it might print something like this during build: `JavaScript input level is NEXT and output level is ES5`). – Jonas Osburg Nov 19 '19 at 12:05
  • Please see here for reference (Sencha CMD 6.5 Changelog): https://docs.sencha.com/cmd/7.0.0/guides/whats_new_cmd65.html#whats_new_cmd65_-_beyond_es6 – Jonas Osburg Nov 19 '19 at 12:14