How to wait for a loop creating streams to finish before saving?

Viewed 1175

I have a problem with knowing when the loop is finished,

app.post('/api/books', upload.array('images'), function(req, res) {
    let book = req.body.book;
    let arr = [];

    // GridFS get connection with DB   
    var gfs = gridfsstream(conn.db);
    var writestream;

    for (i = 0; i < req.files.length; i++) {
        writestream = gfs.createWriteStream({
            filename: req.files[i].originalname
        });
        fs.createReadStream('uploads/' + req.files[i].filename).pipe(writestream);
        writestream.on("close", function(file) {
            console.log(file.filename + "stored successfully into mongodb using gridfs");
        });
        writestream.on("error", function(file) {
            console.log(file.filename + "not stored into mongodb using gridfs");
        });

        base64(writestream.name, function(response) {
            arr.push(response);
        });
    }

    book.images = arr;
    Book.addBook(book, function(err, book) {
        if (err) {
            throw err;
        }
        res.json(book);
    });
});

The problem is: The array arr is empty when I do

book.images = arr 

I need wait the for loop be finished , but how can i do that?

I know this works because i already put a console.log() and works correctly

base64(writestream.name, function(response) {
    arr.push(response);
});
1 Answers
Related