W
W
Wasya UK2017-05-15 14:49:10
JavaScript
Wasya UK, 2017-05-15 14:49:10

How to properly make a function synchronous via await?

I have an asynchronous function to read information about a file. When selecting all the files (and there can be a lot of them - 100+), I read the information about each, and give it further, but here's the problem - the information is read asynchronously, and the files are transferred without a detailed description. What is the correct way to use await/async to do this?
Here's what happened:
How to pass the metadata correctly?

async function getMetadataSync(file) {        
    musicMetadataReader(file, (err, metadata) => {  
        if (metadata.picture.length > 0) {
            metadata.picture[0].base64String = getDecodedPicture(metadata.picture[0]);
        }
        
        return new Promise((resolve, reject) => {
            resolve(metadata); // metadata (true)
        });
    });
}

I can't get here:
await getMetadataSync(stream)
.then((metadata) => {
    console.log(metadata); // undefined
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deodatuss, 2017-05-15
@dmc1989

should be return musicMetadataReader and used like this:
let metadata = await getMetadataSync(stream);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question