node.js – In Node, how do I get my processing to wait while a promise is being fulfilled?

I have a function called srtHandler (shown here with the irrelevant bits removed).

const srtHandler = async (req, res) => {
  elements.forEach(async (num) => {
    const duration = await procureDuration(file, elementNames[num]);
    script[num].push(duration);
    console.log('>', script[num]);
    -- a bunch of other stuff
    console.log(script) // show my script array has not been updated
  });

It calls procureDuration which in turn calls getDuration which returns a promise.
procureDuration returns the required value which I push into my script array.

The console.log shows the value in the array.

However, when I later on display the script array, the new value has not been added because the processing’s moved on without waiting for the call to procureDuration to do its thing despite the await call.

What can I do about this?

const procureDuration = async (file, elementName) => {
  let duration = await getDuration(file, elementName);
    console.log({duration});
  return duration;
};
const getDuration = (subdirectory, file) => {
    console.log('getting duration of an MP3 file');
    const directoryPath = path.join(__dirname, `../data/${subdirectory}/${file}`);
    return new Promise((resolve, reject) => {
        mp3Duration(directoryPath, (err, duration) => {
            if (err) {
                console.log('error=", "err');
                reject(err);
            } else {
                resolve(duration);
            }
        });
    });
};

Read more here: Source link