掌握JS Promises

时间:2018-02-13 11:18:00

标签: javascript node.js promise

我试图了解承诺,并在这个例子中循环。

我的方案基于将文件上传到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部分包装成一个承诺,到目前为止都没有成功。

1 个答案:

答案 0 :(得分:1)

只需将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)