0

I have a problem when using await in a for loop. Every time it hits the await funtion it executes it fine, but it stops loping through the rest of the array that is looping through. I'm using nodejs with axios to send http request to a restAPI. The function that is in the api is big. So I thought maby that is the problem but it wasn't. Also the api uses its own await functions to, but that wasn't the problem either(As far as I know).

Here is my code for the request

    var files = await globPromise("assets/series/**/*.json");
    var json = null;
    var file = null;
    var series = [];
    for (i = 0; i < files.length; i++) {
        file = files[i];
        var raw = fs.readFileSync(file);
        json = JSON.parse(raw);
        if (json.type === "series") {
            try {
                var userId = null;
                if (req.user == null) {
                    userId = req.query.userid;
                } else {
                    userId = req.user.id;
                }
                const response = await axios.get("http://" + host + "/series/info/" + json.id + "?userid=" + userId);
                series.push(JSON.parse(response.data));
            } catch (error) {
                console.log(error);
                series.push(json);
            }
        }
    }
    res.json(JSON.stringify(series));
});

And also the api side:

app.get('/series/info/:id', async(req, res) => {
    var files = await globPromise("assets/series/**/*.json");
    var json = null;
    var file = null;
    for (i = 0; i < files.length; i++) {
        file = files[i];
        var raw = fs.readFileSync(file);
        json = JSON.parse(raw);
        if (json.type === "series" && json.id === req.params.id) {
            break;
        }
        json = null;
    }

    let path = pathFs.dirname(file) + "/";
    try {
        var seriesFiles = await fsPromise.readdir(path);
        var latestWatchedVideo = null;
        var latestWatchedTime = null;
        var latestWatchTime = null;
        var latestWatchDuration = null;
        var seasonCount = 0;
        var seasons = [];
        for (i = 0; i < seriesFiles.length; i++) {
            seriesFile = seriesFiles[i];
            if (fs.lstatSync(path + "/" + seriesFile).isDirectory()) {
                if (!seriesFile.startsWith("s")) {
                    continue;
                }
                seasonCount++;
                try {
                    var videoFiles = await fsPromise.readdir(path + "/" + seriesFile + "/");
                    var videos = [];
                    for (let i = 0; i < videoFiles.length; i++) {
                        const video = videoFiles[i];
                        if (video.endsWith(".json")) {
                            var rawVideo = fs.readFileSync(path + "/" + seriesFile + "/" + video);
                            videoJson = JSON.parse(rawVideo);
                            const query = util.promisify(con.query).bind(con);
                            var userId = null;
                            if (req.user == null) {
                                userId = req.query.userid;
                            } else {
                                userId = req.user.id;
                            }
                            var results = await query(`SELECT * FROM watched WHERE video_id = "${videoJson.id}" AND user_id = "${userId}"`);
                            if (results.length > 0) {
                                var updated = JSON.parse(JSON.stringify(results[0].updated));
                                var duration = JSON.parse(JSON.stringify(results[0].duration));
                                var time = JSON.parse(JSON.stringify(results[0].time));
                                if (latestWatchedVideo == null) {
                                    latestWatchedVideo = videoJson.id;
                                    latestWatchedTime = updated;
                                    latestWatchTime = time;
                                    latestWatchDuration = duration;
                                } else {
                                    if (latestWatchedTime < updated) {
                                        latestWatchedVideo = videoJson.id;
                                        latestWatchedTime = updated;
                                        latestWatchTime = time;
                                        latestWatchDuration = duration;
                                    }
                                }
                            }
                            videos.push(videoJson);
                        }
                    }

                    function compare(a, b) {
                        if (a.episode < b.episode) {
                            return -1;
                        }
                        if (a.episode > b.episode) {
                            return 1;
                        }
                        return 0;
                    }

                    videos.sort(compare);
                    seasons.push({
                        season: seasonCount,
                        title: seriesFile.replace("s" + seasonCount, ""),
                        videos: videos
                    });
                } catch (error) {
                    console.log(error);
                }
            }
        }
        json.seasonCount = seasonCount;
        json.seasons = seasons;
        json.latestWatchDuration = latestWatchDuration;
        json.latestWatchTime = latestWatchTime;
        json.latestWatchedVideo = latestWatchedVideo;
        json.latestWatchedTime = latestWatchedTime;

        res.json(JSON.stringify(json));
    } catch (error) {
        console.log(error);
    }
});

Is there something (important) about await and async that I've missed?

Edit: my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array.

Solved: I tried using the for/of and it works now. I don't know whats is so different between de default for and this one but it works!

DJ1TJOO
  • 3
  • 4
  • 3
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Seblor Apr 13 '20 at 13:14
  • No, my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array – DJ1TJOO Apr 13 '20 at 20:03
  • Your `i` variable is global, which is just asking for trouble. Declare a local variable. – Bergi Apr 13 '20 at 20:12
  • Maybe a stupid question, but I'm going for it: Is is absolutely certain that you have more than one element in your array which satisfies the condition `json.type === "series"`? – abondoa Apr 13 '20 at 20:31
  • I have 2 files with the type string only one is doing every thing in the for loop (the first one) – DJ1TJOO Apr 14 '20 at 11:34
  • @Bergi that did not help, but I've changed it to a local variable – DJ1TJOO Apr 14 '20 at 11:38

0 Answers0