Reputation: 3414
My problem is I'm trying to await on some promises, but my await call seems to return to the calling function right away.
In the code below (part of a controller function handling a POST), the "files coming out" log after my function call is executed prior to the promises being executed. My async function seemingly returns at the "await" call.
However the "await" still does wait for all the promises to execute, so the "I just finished waiting" log does have the magic var inserted into the req.files
correctly.
const upload = multer({
storage: multer.diskStorage ({
destination: (req, file, cb) => { cb(null, config.DESTINATION) }
})
}).array(config.FIELD_NAME);
exports.upload_image = function(req, res) {
upload(req, res, (err) => {
if (err) {
return res.end("error uploading file");
}
// got file ok, do validation
checkAreDicom2( req.files );
console.log("files coming out: ", req.files);
return res.end("OK");
});
}
async function checkAreDicom2(inFiles) {
let promises = inFiles.map(function (file) {
return new Promise( function (resolve, reject) {
fs.createReadStream(file.path,{start: 128, end: 131, autoClose: true})
.on('error',reject)
.on('data', (chunk) => file.magic = file.magic ? file.magic += chunk : chunk)
.on('end', resolve);
});
});
await Promise.all(promises);
console.log("i just finished waiting: ", inFiles);
return;
}
Upvotes: 0
Views: 290
Reputation: 664969
The await
is waiting for the Promise.all
, and the log after it is correctly delayed. However it does of course not block the caller of function.
So the callback in upload_image
does not wait for the asynchronous processing, it just receives the promise that checkAreDicom2(…)
returns - and discards it, and immediately logs something. You would need to await the asynchronous result explicitly here again.
exports.upload_image = async function(req, res) {
try {
await new Promise((resolve, reject) => {
upload(req, res, (err) => {
if (err) reject(err);
else resolve();
});
});
// got file ok, do validation
await checkAreDicom2( req.files );
// ^^^^^
console.log("files coming out: ", req.files);
return res.end("OK");
} catch(err) {
return res.end("error uploading file");
}
};
Upvotes: 1