For-loop order (with asynchronous function)

246
December 19, 2017, at 11:49 PM

I have this code :

exports.formatDepArrTables = function(jsonReturn, type, placeName, callback) {
    let toSend = "";
    if (type == 'departure') {
        for (let j = 0; j < jsonReturn.departures.length; j++) {
            console.log("DEPARTURES LOOP j = " + j + "/" + jsonReturn.departures.length);
            if(currentDeparture.display_informations.links[0] === undefined) {
                toSend += ""; // setting some string informations
            }
            else {
                let oceTrainId = ""; // random number given by a json
                _this.getDisruptionFromDisruptionId(oceTrainId, function(data) {
                    for(let i = 0; i < data.disruptions[0].impacted_objects[0].impacted_stops.length; i++) {
                        if(currentImpactedStop.stop_point.label == placeName) {
                            toSend += "string";
                        }
                    }
                });
            }
        }
        console.log("End of the first loop");
        return callback(toSend);
    } else if (type == 'arrival') {
        // copy&paste
    } else {
        throw new Error("not defined");
    }
};

When I run this code (I use NodeJS), it makes 1/10, 2/10... from the first loop but it didn't iterate the second loop on the 1st iteration of the first loop (and it shows "End of the first loop" and starts the second loop).

getDisruptionFromDisruptionId is a custom method which makes a request (with 'request' NodeJS module) on an API.

Of course, I need to have informations given by getDisruptionFromDisruptionId to run my next loop...

Parent function of this code part is returning a callback that needs to be "filled" at the end of the both two loops.

Any ideas ?

Answer 1

request is async function, you need to add async / await to your code or use recursion

READ ALSO
Atlassian-connect: Error on &#39;installed&#39; event

Atlassian-connect: Error on 'installed' event

I'm trying to run example Jira add-onI have created credentials

158
Empty request body

Empty request body

I generated two projects, one with create-react-app and the other with express generator

215
How to render data in proper format in PDF using hbs file.

How to render data in proper format in PDF using hbs file.

I have an array of object named attribute which I need to bind in hbs fileI passed this object successfully as I can see data there in hbs file

212
Sails JS - Nested .query method doesn&#39;t run sequence

Sails JS - Nested .query method doesn't run sequence

I beginner in Sails JSI try to make multiple

186