首页 > 解决方案 > 有没有一种方法可以让我在返回结果之前等待 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
    });
});

}

标签: javascriptasynchronousasync-await

解决方案


推荐阅读