javascript - 有没有一种方法可以让我在返回结果之前等待 javascript 函数完成
问题描述
我想在返回结果之前运行函数 preProcessed(),以便该消息具有正确的数据。我尝试等待 preProcessed() 并使地图异步,但随后数据为空。解决问题的最佳方法是什么。
exports.get_by_notifier = (req, res, next) => {
const userId = parseInt(req.params.id)
Notification.findAndCountAll({
include: [
{
model: NotificationNotifier,
where: {
userId: userId
},
}
]
})
.then(result => {
if (!result) {
res.status(404).json({
error: 'Notification Not Found',
});
} else {
const response = {
data: result.rows.map(async notification => {
var message
const entity_type_id = notification.entityTypeId
const originalData = notification
const preProcess = entityTypeDetails[entity_type_id].process;
async function getPreprocessed() {
let processedData = []
const promise = entityTypeDetails[entity_type_id].preProcessing
for (let index = 0; index < promise.length; index++) {
const element = promise[index];
const processed = await element.process(originalData)
processedData.push(processed)
}
processedData = Object.assign({}, ...processedData.map(object => (object)))
message = res.__(entityTypeDetails[entity_type_id].messageProp,processedData)
}
if (preProcess === 1) {
await getPreprocessed()
} else {
message = res.__(entityTypeDetails[entity_type_id].messageProp)
}
return {
message: message
}
})
}
res.status(200).json(response)
}
})
.catch(err => {
res.status(500).json({
error: err.message
});
});
}
解决方案
推荐阅读
- rabbitmq - 测试 SpringCloudStream Consumer 的最小上下文
- json - jq将元素添加到对象数组中的每个对象
- mailgun - 使用 mailgun-js v0.8.1 挂断套接字
- web-applications - 具有实时数据的 Web 应用程序流程图/流程图
- jestjs - 如何在 NodeJS 和 jest 中记录深度堆栈跟踪?
- css - 将标签移动到待办事项栏的顶部
- c# - 我正在尝试在我的项目中混合使用 netstandard2.0 和 net48,以逐步过渡到 .NET Core。如何解决此管道警告?
- django - 请求总是返回从 React-Native 发送到 Django 的未经授权的
- php - 如何在php中上传pdf或doc或txt文件
- mysql - 截断作为 CONCAT 函数结果的列?