gpt4 book ai didi

javascript - 火力地堡 : Convert promise to async/await

转载 作者:行者123 更新时间:2023-11-28 03:11:50 25 4
gpt4 key购买 nike

下面是使用 Promise(.then) 的代码片段,它工作正常,但是当我将其转换为 async wait 时,我收到一个错误,该错误被捕获 block

promise -

exports.createScream = functions.https.onRequest((req, res) => {
if (req.method !== "POST") {
return res.status(400).json({ error: "Method not allowed" });
}
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: admin.firestore.Timestamp.fromDate(new Date())
};
admin
.firestore()
.collection("screams")
.add(newScream)
.then(doc => {
res.json({ message: `document ${doc.id} created successfully` });
})
.catch(err => {
res.status(500).json({ error: "something went wrong" });
console.error(err);
});
});

异步/等待 -

exports.createScream = functions.https.onRequest(async (req, res) => {
if (req.method !== "POST") {
return res.status(400).json({ error: "Method not allowed" });
}

try {
const newScream = {
body: req.body.body,
userHandle: req.body.userHandle,
createdAt: admin.firestore.Timestamp.fromDate(new Date())
};
const res = await admin
.firestore()
.collection("screams")
.add(newScream);
return res.json({
message: `document ${doc.id} created successfully`
});
} catch (err) {
console.error(err);
return res.status(500).json({ error: "something went wrong" });
}
});

请让我知道代码的 Async/Await 部分有什么问题

最佳答案

根据@user2222上面的评论const doc = wait admin .firestore() .collection("screams") .add(newScream);解决了问题

关于javascript - 火力地堡 : Convert promise to async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60027491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com