Reputation: 15384
I'm trying to get my head around promises, and in this instance within a loop.
My scenario is based around uploading files to Google Drive. My understanding is that each file should upload and then once the promise is resolved upload the next, and so on.
At the moment I have a function that will upload a file and return a promise once completed:
# upload.js
const google = require('googleapis');
const drive = google.drive('v3');
function uploadFile(jwtClient, fileMetadata, media) {
return new Promise((resolve, reject) => {
drive.files.create({
auth: jwtClient,
resource: fileMetadata,
media,
fields: 'id, modifiedTime, originalFilename'
}, (err, uploadedFile) => {
if (err) reject(err);
// Promise is resolved with the result of create call
console.log("File Uploaded: " + uploadedFile.data.originalFilename);
resolve(uploadedFile)
});
});
}
module.exports = uploadFile;
I then want to use this function in a loop, my thinking here is that the next iteration of the loop should not happen until the promise is returned from the uploadFile
function
const google = require('googleapis');
const uploadFile = require('./components/upload');
const config = require('./gamechanger-creds.json');
const drive = google.drive('v3');
const targetFolderId = "1234"
var excel_files_array = [array if file names];
const jwtClient = new google.auth.JWT(
config.client_email,
null,
config.private_key,
['https://www.googleapis.com/auth/drive'],
null
);
jwtClient.authorize((authErr) => {
if (authErr) {
console.log(authErr);
return;
}
for(var i = 0; i < excel_files_array.length; i++) {
console.log("File Name is: " + excel_files_array[i]);
const fileMetadata = {
name: excel_files_array[i],
parents: [targetFolderId]
};
const media = {
mimeType: 'application/vnd.ms-excel',
body: fs.createReadStream('path/to/folder' + excel_files_array[i] )
};
uploadFile(jwtClient, fileMetadata, media);
}
});
When running this my output is as follows
File Name is: arsenal_away.xlsx
File Name is: bournemouth_away.xlsx
File Name is: brighton_away.xlsx
File Name is: burnley_away.xlsx
File Name is: chelsea_away.xlsx
File Name is: crystal_palace_away.xlsx
File Name is: everton_away.xlsx
File Uploaded: undefined
(node:83552) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 7): Error: Invalid multipart request with 0 mime parts.
(node:83552) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
File Uploaded: undefined
(node:83552) UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 9): Error: Invalid multipart request with 0 mime parts.
File Uploaded: undefined
File Uploaded: bournemouth_away.xlsx
File Uploaded: everton_away.xlsx
File Uploaded: burnley_away.xlsx
File Uploaded: arsenal_away.xlsx
File Uploaded: brighton_away.xlsx
File Uploaded: chelsea_away.xlsx
File Uploaded: crystal_palace_away.xlsx
So the file uploads are not happening in order (not sure if they are supposed to be? guess not because its all happening asynchronously).
I'm looking to learn how to ensure these are uploaded in order (if that indeed is the best way) and to ensure the file upload resolves the promise before moving onto the next file.
I was also hoping I could wrap the auth part of my script into a promise to, unsuccessful so far.
Upvotes: 0
Views: 123
Reputation: 215039
Just put async/await
where they belong
async function uploadFile(jwtClient, fileMetadata, media) ...
async function uploadManyFiles(...)
for(....)
await uploadFile(...)
This ensures uploads are executed in order. If you want them to happen in parallel, then group the promises into .all
:
await Promise.all(files.map(uploadFile))
With the auth it's exactly the same as with uploads:
async function auth(...)
return new Promise((resolve, reject) => {
jwtClient = ...
jwtClient.authorize((authErr) => {
if (authErr) {
reject(authErr);
else
resolve(whatever)
Upvotes: 1