Javascript 以“For循环”(异步)方式上载到Google云存储
我是Javascript新手。我正在尝试创建一个循环,将图像上传到谷歌云存储。使用此代码,可以正确上载图像。问题是上传后路径URL没有保存在数据库中 我尝试使用async并等待。然而,我不明白它是如何工作的。我希望for循环和里面的所有内容都在保存帖子之前完成 提前谢谢大家,Javascript 以“For循环”(异步)方式上载到Google云存储,javascript,node.js,google-cloud-platform,google-cloud-storage,nodejs-stream,Javascript,Node.js,Google Cloud Platform,Google Cloud Storage,Nodejs Stream,我是Javascript新手。我正在尝试创建一个循环,将图像上传到谷歌云存储。使用此代码,可以正确上载图像。问题是上传后路径URL没有保存在数据库中 我尝试使用async并等待。然而,我不明白它是如何工作的。我希望for循环和里面的所有内容都在保存帖子之前完成 提前谢谢大家, for (const [i, file] of files.entries()) { newFileName = "img_" + Date.now() + "_" + file.originalname; ima
for (const [i, file] of files.entries()) {
newFileName = "img_" + Date.now() + "_" + file.originalname;
imagePath = getPublicUrl(newFileName);
myfile = bucket.file(newFileName);
stream = myfile.createWriteStream({
metadata: {contentType: file.mimetype},
resumable: false
});
sharp(file.buffer)
.resize({ width: 1080 })
.pipe(stream)
.on('finish', () => {
post.images.push(imagePath);
})
}
post.save();
您希望为每个请求创建一个挂起承诺数组,然后可以将它们包装在Promise方法Promise.all[]中 例如:
// we'll push all the promises into this array:
const pendingPromises = []
for (const {i, file} of files.entries()) {
// just wrap it in a promise
// and push into the promise array:
pendingPromises.push(new Promise((resolve, reject) => {
// do everything the same as before for each iteration
newFileName = "img_" + Date.now() + "_" + file.originalname;
imagePath = getPublicUrl(newFileName);
myfile = bucket.file(newFileName);
stream = myfile.createWriteStream({
metadata: {contentType: file.mimetype},
resumable: false
});
sharp(file.buffer)
.resize({ width: 1080 })
.pipe(stream)
.on('finish', () => {
post.images.push(imagePath);
resolve(imagePath)
})
}))
}
// wait for all the async code to complete execution and resolve before saving the posts:
Promise.all(pendingPromises)
.then(imagePaths => post.save()) /*<-- all the promises resolved without errors, now you can save*/
.catch(() => console.log('well that didnt work...'))
您需要学习JavaScript Promise语言的特性。你在文章中用async和Wait提到了这一点。将循环的每次迭代看作是向数组添加新的承诺。当在循环中启动的异步工作完成时,您将解析该迭代添加的承诺。在循环结束时,您将阻塞一个Promise.all,它等待数组中的所有承诺完成。我建议你坚持承诺,如果你在这方面有问题。。。经过研究。。。就这个话题发表一个问题。