sách gpt4 ai đã đi

javascript - 掌握 JS Promise

In lại 作者:行者123 更新时间:2023-12-03 02:30:07 26 4
mua khóa gpt4 Nike

我正在尝试理解 promise ,在本例中是在一个循环中。

我的场景基于将文件上传到 Google 云端硬盘。我的理解是,每个文件都应该上传,然后一旦 promise 得到解决,就上传下一个文件,依此类推。

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

# 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'],
vô giá trị
);

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

所以文件上传没有按顺序发生(不确定它们是否应该如此?猜不是因为它都是异步发生的)。

我希望了解如何确保这些文件按顺序上传(如果这确实是最好的方法),并确保文件上传在移至下一个文件之前解决 promise 。

我还希望能够将脚本的身份验证部分包装成一个 promise ,但到目前为止尚未成功。

1 Câu trả lời

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

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

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

这可确保上传按顺序执行。如果您希望它们并行发生,请将 promise 分组到 .all ở giữa:

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

使用身份验证与上传完全相同:

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

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

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com