[英]Two asynchronous codes in two different files. I want them to run one by one but they run at the same time
The code in the second file depends upon the first one so I want the first file code to execute first and when the first file code completes it's execution then the code in second file should run.第二个文件中的代码取决于第一个文件,所以我希望第一个文件代码首先执行,当第一个文件代码完成它的执行时,第二个文件中的代码应该运行。 The code in the first file basically stores the image in the google cloud bucket and then return the URL of that image and second file updates the post schema in MongoDB and pushes the URL string in the images array.
第一个文件中的代码基本上将图像存储在谷歌云存储桶中,然后返回该图像的 URL,第二个文件更新 MongoDB 中的帖子模式并将 ZE6B391A8D2C4D45902A23A8B658 中的字符串推送到图像数组中。 Since the code in both files runs side by side and the code in the second files does not wait for first one to execute the post schema is updated even before the first code returns all the string url's which is a problem.
由于两个文件中的代码并排运行,并且第二个文件中的代码不会等待第一个文件执行后模式,因此即使在第一个代码返回所有字符串 url 之前,它也会更新,这是一个问题。 I want to get all the string url's first and then update the post schema.
我想先获取所有字符串 url,然后更新帖子架构。
So in first file I have所以在第一个文件中我有
function sendUploadsToGCS(req, res, next){
if(!req.files){
return next();
}
req.files.map((image, index) => {
const gcsname = uuid() + image.originalname;
const file = craigFilesBucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: image.mimetype,
}
});
stream.on('error', err =>{
req.files[index].cloudStorageError = err;
next(err);
});
stream.on('finish', async () => {
req.files[index].cloudStorageObject = gcsname;
await file.makePublic();
req.files[index].cloudStoragePublicUrl = getPublicUrl(gcsname);
console.log(req.files[index].cloudStoragePublicUrl);
next();
});
stream.end(image.buffer);
})
}
In the second file I have在我的第二个文件中
const addImagestoPost = async (req, res, next) =>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return next(new HttpError('Invalid inputs passed, please check your data.', 422))
}
const postId = req.params.pid;
let post;
try{
post = await Post.findById(postId);
}catch(err){
const error = new HttpError(
'Something went wrong could not update post',
500
);
return next(error);
}
// if(!req.files[0] || !req.files[0].cloudStoragePublicUrl){
// return next(new HttpError('cloudStoragePublicUrl err.', 422))
// }
//images: req.files.cloudStoragePublicUrl,
console.log('HEllo World');
try{
await post.save();
}catch(err){
const error = new HttpError(
'Something went wrong, could not update post', 500
)
}
res.status(200).json({post: post.toObject({getters: true})})
}
You may arrange your code like mentioned below:您可以安排您的代码,如下所述:
const func1 = require(from file 1);
const func2 = require(from file 2);
async function load() {
const result1 = await func1();
const result2 = await func2()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.