我正在努力兑现诺言,在这种情况下是一个循环。

我的情况基于将文件上传到Google云端硬盘。我的理解是,每个文件都应该上传,然后在诺言解决之后再上传下一个,依此类推。

目前,我有一个可以上传文件并在完成后返回承诺的函数:

# 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;


然后,我想在循环中使用此函数,我的想法是在uploadFile函数返回promise之前,不应进行循环的下一次迭代

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);

 }
});


运行此命令时,我的输出如下

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


因此,文件上载没有按顺序进行(不确定是否应该上载吗?不要猜测是因为所有这些都是异步发生的)。

我正在研究如何确保按顺序上载这些文件(如果确实是最好的方法),并确保在上一个文件之前文件上载能够解决诺言。

我也希望我可以将脚本的auth部分包装成一个承诺,但到目前为止没有成功。

最佳答案

只需将async/await放在它们所属的位置

async function uploadFile(jwtClient, fileMetadata, media) ...

async function uploadManyFiles(...)
    for(....)
       await uploadFile(...)


这样可确保按顺序执行上传。如果希望它们并行发生,则将诺言分组为.all

  await Promise.all(files.map(uploadFile))


使用auth与上载完全相同:

async function auth(...)
    return new Promise((resolve, reject) => {
       jwtClient = ...
       jwtClient.authorize((authErr) => {
         if (authErr) {
             reject(authErr);
         else
             resolve(whatever)

关于javascript - 掌握JS Promises,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48765590/

10-13 01:55