我在Express中有一个需要验证的帖子,因此我创建了一个名为“ validator.js”的javascript文件,以在继续操作之前检查传递的值。 “ validator.js”中的方法之一需要进行axios调用,但是显然需要时间才能完全填充数据。所以我像这样用async / await解决了
router.post("/add_to_favorites", passport.authenticate("local"), async(req, res) =>
{ let validation = await validateMedia(req.body);
if (validation.error) {
return res.status(400).json(validation.message);
}
“ validateMedia”是调用validator.js的函数。
快递
router.post("/add_to_favorites", passport.authenticate("local"), (req, res) =>
{ let validation = validateMedia(req.body);
if (validation.error) {
return res.status(400).json(validation.message);
}
}
validator.js
const validateMedia = data => {
if (data.mediaType !== "movie" && data.mediaType !== "serie") {
return {
error: true,
message: "Media type is not valid"
};
}
if (data.mediaType === "movie") {
axios.get(`/${data.mediaType}/${data.mediaId}`).then(response => {
if (data.mediaTitle === response.data.title) {
return { error: false, message: "Success" };
}
return { error: true, message: "Failed" };
});
}
return { error: false, message: "Checked values" };
}
答案 0 :(得分:0)
您共享了有限的信息。是否需要定义validateMedia
的方式,它使用new Promise
返回Promise还是async
函数?在async-await
中,await
等待承诺得到解决。
详细了解async-await和promise here。
如果validateMedia
函数类似于:
承诺:
function validateMedia(data) {
// Using promise here
return new Promise ( (resolve, reject) => {
if (data.mediaType !== "movie" && data.mediaType !== "serie") {
return resolve({ // Call resolve function to return success
error: true,
message: "Media type is not valid"
});
}
if (data.mediaType === "movie") {
// This is the function needs to wait for.
axios.get(`/${data.mediaType}/${data.mediaId}`).then(response => {
if (data.mediaTitle === response.data.title) {
// Call resolve function to return success
return resolve({ error: false, message: "Success" });
}
// Call reject function to return error
return reject({ error: true, message: "Failed" });
});
}
});
}
使用异步等待:
async function validateMedia(data) {
if (data.mediaType !== "movie" && data.mediaType !== "serie") {
return {
error: true,
message: "Media type is not valid"
};
}
if (data.mediaType === "movie") {
try {
// This is the function needs to wait for. if axios.get() returns a promise
let response = await axios.get(`/${data.mediaType}/${data.mediaId}`);
if (data.mediaTitle === response.data.title) {
return { error: false, message: "Success" };
}
return { error: true, message: "Failed" };
}
// If axios.get() throws error or rejects promise
catch (err) {
return { error: true, message: "Failed" };
}
}
}