W
W
Wasya UK2017-05-14 20:04:01
JavaScript
Wasya UK, 2017-05-14 20:04:01

Why doesn't async.each make execution synchronous?

With the following code, the result check function is executed first:

async.forEachOf(audios, function(audio, key, callback) {
    Audio.getMetadata(audio.path, function(err, metadata) { // асинхронная
        if (err) {
            console.log(err);
            return callback(err);
        }

        fullAudios.push(Audio.setMetadata(audio, metadata)); // return audio with metadata
        callback();
    });
}, function done(err) {
    if (err) {
        console.log(err);
    } 

    console.log(fullAudios);
});

How can I check for the presence of all files, and then return an array from the finds, if the check function is asynchronous?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
Wasya UK, 2017-05-16
@dmc1989

And so, here is my solution, not the fact that the code is correct, but it works.

module.exports.getMetadates = async function getMetadates(audios) {
    return await Promise.all(audios.filter((audio) => fs.existsSync(audio.path)).map(async function(audio) {
        let stream = fs.createReadStream(audio.path);
        let metadata = await getMetadataSync(stream);
    
        return Audio.setMetadata(audio, metadata);
    }));
}
async function getMetadataSync(file) {        
    return await new Promise ((resolve, reject) => {
        musicMetadataReader(file, (err, metadata) => {
             if (err) {
                 return reject(err);
             }
             if (metadata.picture.length > 0) {
                  metadata.picture[0].base64String = getDecodedPicture(metadata.picture[0]);
             }
             resolve(metadata); 
        });
    });
}

N
Negwereth, 2017-05-14
@Negwereth

Promise

D
Dark Hole, 2017-05-14
@abyrkov

Only with await

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question