node.js - 异步/等待发布请求 - nodejs
问题描述
在继续我的 POST 请求的其余部分之前,我需要进行数据库调用并等待它的响应(在这种情况下等待承诺被履行)。
app.post("/charge", (req, res) => {
var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}
但是我不能等待查询,因为我不在异步函数中。我怎样才能使app.post
异步?
在其他路线中,我已经这样做了
app.get('/', async function (req, res) {
const leagues = await distinctLeagues();
res.render('home', { leagues: leagues });
});
但我想知道如何使用箭头函数语法来做到这一点。
解决方案
你可以在 es6 中创建一个async
函数,如下所示:
app.post("/charge", async (req, res) => {
var user_stripe_id = await queries.get_stripe_id_by_email(req.body.token.email);
}
这是 async-await 的理想用法,在 try-catch 中使用它。由 Promise 解析的值将被分配给quote
,如果 Promise 被拒绝,则将执行 catch 块。
async function main() {
try {
var quote = await getQuote();
console.log(quote);
} catch (error) {
console.error(error);
}
}
推荐阅读
- c# - 为什么我的实现总是调用同一个派生类?
- jqgrid - jqgrid中的下拉菜单仅在双击时显示
- docker - 如何将 Azure Web 应用程序移动到容器
- reactjs - 酶无法识别我创建的子组件
- excel - 有没有办法以类似于 TextBox_AfterUpdate 的方式检查标签框是否已更新?
- javascript - 使用 JavaScript 将 null 替换为字符串
- php - 为什么不满足标准参数时我的 SQL 会给出结果
- laravel - 我想将 laravel Web 应用程序部署到 live 中?
- excel - vba初始化字典的早期和后期绑定
- html - 如何在页面加载后填写输入表单?