首页 > 解决方案 > 如何进行并行异步/等待 api 标注

问题描述

我是 Async / Await 的新手,并尝试使用 Node.js 进行这 3 个标注以并行获取 Google Drive 元数据。3 个标注是:rootFolderfoldersfiles

由于这些调用getGdriveList本身是异步函数并包含await. 这await是需要的,因为 API 返回一页记录,我需要遍历所有页面以获取记录。我使用await来等待 API 响应并将数据添加到数组中。此过程呈现代码以串行运行。

我正在寻求帮助来重构以使其平行。提前致谢

const {google} = require('googleapis');
const gOAuth = require('./googleOAuth')
const aws = require('aws-sdk');

// initialize google oauth credentenatials 
let readCredentials = gOAuth.readOauthDetails('credentials.json')
let authorized = gOAuth.authorize(readCredentials, getGfiles)

// get Google meta data on files and folders
function getGfiles(auth) {
  let rootFolder = getGdriveList(auth, {corpora: 'user', 
                                        fields: 'files(name, parents)', 
                                        q: "'root' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder'"})

  let folders = getGdriveList(auth, {corpora: 'user', 
                                    fields: 'files(id,name,parents), nextPageToken', 
                                    q: "trashed = false and mimeType = 'application/vnd.google-apps.folder'"})

  let files = getGdriveList(auth, {corpora: 'user', 
                                    fields: 'files(id,name,parents, mimeType), nextPageToken', 
                                    q: "trashed = false and mimeType != 'application/vnd.google-apps.folder'"})

  files.then(result => {console.log(result)})
}

const getGdriveList = async (auth, params) => {
  let list = []
  let nextPgToken
  const drive = google.drive({version: 'v3', auth})
  do {
    let res = await drive.files.list(params)
    list.push(...res.data.files)
    nextPgToken = res.data.nextPageToken
    params.pageToken = nextPgToken
  }
  while (nextPgToken)
  return list
}

标签: javascriptasync-await

解决方案


扩展@CameronTacklind 的答案,数组解构是更惯用的方法。

const [rootFolder, folders, files] = await Promise.all([
  getGdriveList(...),
  getGdriveList(...),
  getGdriveList(...),
]);

// more code ...

推荐阅读