代码工作并将图像上传到Backblaze
,但它不会等待for循环完成运行和查询在调用下一个之前完成。如果我控制台记录文件id,它将在调用next()
后3或4秒列出id !
import fs from "fs";
import B2 from "backblaze-b2";
import path from "path";
import dotenv from "dotenv";
dotenv.config();
export const uploadToBackBlaze = async (req, res, next) => {
console.log("I'm here uploading to Backblaze");
const b2 = new B2({
applicationKeyId: process.env.BACKBLAZE_ACCOUNT_ID,
applicationKey: process.env.BACKBLAZE_MASTER_APPLICATION_ID,
});
const __dirname = path.resolve();
let tempDir = path.join(__dirname, "chapterTemp");
const imageIds = [];
try {
b2.authorize()
.then(async () => {
const bucketId = process.env.BACKBLAZE_BUCKET_ID;
fs.readdir(tempDir, async function (err, files) {
if (err) {
console.error(err);
res.sendStatus(500).json({ message: err.message });
return;
}
for (const file of files) {
const fileData = fs.readFileSync(path.join(tempDir, file));
const uploadFileName = path.join(file);
const uploadUrl = await b2.getUploadUrl(bucketId);
const response = await b2.uploadFile({
uploadUrl: uploadUrl.data.uploadUrl,
uploadAuthToken: uploadUrl.data.authorizationToken,
filename: uploadFileName,
data: fileData,
mime: "image/png" || "image/jpg" || "image/jpeg" || "image/webp", // replace with the appropriate MIME type for your files
});
console.log(response.data.fileId);
imageIds.push(response.data.fileId);
}
});
})
.then(() => {
console.log(imageIds);
req.imageIds = imageIds;
next();
});
} catch (error) {
console.log(error);
return res.status(500).json({ message: error.message });
}
};
我希望它完成等待for循环,并在调用next之前将id推入数组,这样我就可以将id存储在数据库中!
问题的根本原因是,正如@jfriend00在评论中所说,fs.readdir()
是一个普通的回调异步函数。因此,当fs.readdir()
仍在运行时,执行将继续到包含next()
的then()
。@jfriend00也提到,混合使用then()
和await
会使代码更加复杂,难以正确编写。
这里有一个可用的版本。它使用fs.readdirSync()
,它只是返回文件数组,并将then()
替换为await以使代码更容易理解。
import fs from "fs";
import B2 from "backblaze-b2";
import path from "path";
import dotenv from "dotenv";
dotenv.config();
export const uploadToBackBlaze = async (req, res, next) => {
console.log("I'm here uploading to Backblaze");
const b2 = new B2({
applicationKeyId: process.env.BACKBLAZE_ACCOUNT_ID,
applicationKey: process.env.BACKBLAZE_MASTER_APPLICATION_ID,
});
const __dirname = path.resolve();
let tempDir = path.join(__dirname, "chapterTemp");
const imageIds = [];
try {
await b2.authorize();
const bucketId = process.env.BACKBLAZE_BUCKET_ID;
const files = fs.readdirSync(tempDir);
for (const file of files) {
const fileData = fs.readFileSync(path.join(tempDir, file));
const uploadFileName = path.join(file);
const uploadUrl = await b2.getUploadUrl(bucketId);
const response = await b2.uploadFile({
uploadUrl: uploadUrl.data.uploadUrl,
uploadAuthToken: uploadUrl.data.authorizationToken,
filename: uploadFileName,
data: fileData,
mime: "image/png" || "image/jpg" || "image/jpeg" || "image/webp", // replace with the appropriate MIME type for your files
});
console.log(response.data.fileId);
imageIds.push(response.data.fileId);
}
console.log(imageIds);
req.imageIds = imageIds;
next();
} catch (error) {
console.log(error);
return res.status(500).json({ message: error.message });
}
};
输出:
I'm here uploading to Backblaze
4_z0145cfc9e3f5ec0f74ed0c1b_f117d3fad62e89e20_d20230402_m183653_c004_v0402012_t0031_u01680460613262
4_z0145cfc9e3f5ec0f74ed0c1b_f106c056c78a74bfd_d20230402_m183653_c004_v0402006_t0016_u01680460613601
4_z0145cfc9e3f5ec0f74ed0c1b_f10983156bddd6e1d_d20230402_m183654_c004_v0402001_t0002_u01680460614026
4_z0145cfc9e3f5ec0f74ed0c1b_f110cce66726eafc9_d20230402_m183654_c004_v0402002_t0004_u01680460614244
4_z0145cfc9e3f5ec0f74ed0c1b_f11877e4fecf8da12_d20230402_m183654_c004_v0402012_t0026_u01680460614505
4_z0145cfc9e3f5ec0f74ed0c1b_f107e976b612ad7d0_d20230402_m183654_c004_v0402005_t0057_u01680460614840
[
'4_z0145cfc9e3f5ec0f74ed0c1b_f117d3fad62e89e20_d20230402_m183653_c004_v0402012_t0031_u01680460613262',
'4_z0145cfc9e3f5ec0f74ed0c1b_f106c056c78a74bfd_d20230402_m183653_c004_v0402006_t0016_u01680460613601',
'4_z0145cfc9e3f5ec0f74ed0c1b_f10983156bddd6e1d_d20230402_m183654_c004_v0402001_t0002_u01680460614026',
'4_z0145cfc9e3f5ec0f74ed0c1b_f110cce66726eafc9_d20230402_m183654_c004_v0402002_t0004_u01680460614244',
'4_z0145cfc9e3f5ec0f74ed0c1b_f11877e4fecf8da12_d20230402_m183654_c004_v0402012_t0026_u01680460614505',
'4_z0145cfc9e3f5ec0f74ed0c1b_f107e976b612ad7d0_d20230402_m183654_c004_v0402005_t0057_u01680460614840'
]