javascript - 如何进行并行异步/等待 api 标注
问题描述
我是 Async / Await 的新手,并尝试使用 Node.js 进行这 3 个标注以并行获取 Google Drive 元数据。3 个标注是:rootFolder
、folders
、files
。
由于这些调用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
}
解决方案
扩展@CameronTacklind 的答案,数组解构是更惯用的方法。
const [rootFolder, folders, files] = await Promise.all([
getGdriveList(...),
getGdriveList(...),
getGdriveList(...),
]);
// more code ...
推荐阅读
- html - 浏览器缩放期间的 CSS sprite vs Image
- c# - 如何获取在.netcore web api(IFromFile)中选择的路径文件
- javascript - 使用 execCommand 设置 UnorderedList 的前景色
- flutter - Flutter:无法导航到另一个页面
- c - 即使我不尝试修改字符串,为什么还要在 C 中修改字符串?
- python - 通过python将文件从一个目录传输到另一个目录
- c# - 轻按几下如何修复?
- java - 在 Intent 之间传递对象 (intent.putExtra),使用领域对象
- javascript - 将属性分配给另一个 Dto
- sequelize.js - 创建模型后如何急切加载模型?