javascript - 使用 Express 和 Node 从同步函数中调用异步(Promise)函数
问题描述
从基本的 express index.js 文件中,有没有办法从同步函数调用(这里的getData)中调用异步函数?
const express = require('express');
const bodyParser = require('body-parser');
// function which calls a Promise
const getData = require('./getAsyncData.js');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/authors/:lang', (req, res) => {
const lang = req.params.lang;
const getResults = getData( lang );
res.json(getResults);
});
这就是 getAsyncData 模块的样子:
// getAsyncData.js
const getAsyncData = async function () {
try {
// Questionable method of recovering the lang parameter here.
const lang = (arguments.length) ? arguments[0].toUpperCase() : null;
// Connect to the database
const connection = await db.connect(true);
// Get the data
const {authors, books} = await connection.load();
// Join results and filter it
const filtered_results = GetAuhtorsBooks(authors, books, lang);
// Send it back
return filtered_results;
} catch(e) {
return null;
}
};
module.exports = getAsyncData;
但是在index.js
调用中getData
不可避免地发生在getAsyncData
模块内部的调用之前。getData
给undefined
. 似乎获得结果的唯一方法是在index.js
:
app.get('/authors/:lang', async (req, res, next) => {
try {
const lang = req.params.lang;
const testResult = await runTests(lang);
res.json(testResult);
} catch (e) {
//this will eventually be handled by the error handling middleware
next(e)
}
});
有没有 在 app.get(...) 中实现异步/等待功能的情况下获得相同结果的方法?
非常感谢您的任何建议。
解决方案
您可以使用较低级别的 API.then()
app.get('/authors/:lang', (req, res, next) => {
const lang = req.params.lang;
getData( lang )
.then(getResults => res.json(getResults));
.catch(next);
});
但在这一点上,你最好使用async
,尤其是当你的代码达到一个点,即只获取一个数据点并返回它是不够的,你需要做更多的事情。
您仍然需要手动调用,next()
或者res.error(...)
无论如何,一旦涉及 Promise,您的函数将不再同步抛出或错误。
推荐阅读
- sql - 在 postgresql 中标记日期格式的案例语句
- javascript - 如何将 react 导入我的 background.js chrome 扩展
- sql - 如何在 SQL Server 中重命名数据库?
- laravel - Laravel src/Controllers/StatisticsController.php 找不到路径
- css - 如何在 SASS 中生成动态变量
- android - 线程“主”java.lang.NoClassDefFoundError 中的异常:javax/xml/bind/annotation/XmlSchema EXCEPTION
- android - 将数据设置到启动此 nav_graph/fragment 的 nav_graph/fragment 的视图模型,而不知道是谁启动了此 nav_graph
- django - Django - 按自定义函数排序
- python - Python:实现__str__方法后保留对象的内存地址
- pandas - pandas 中的稀疏列:直接访问非空值的索引