如何在异步Express函数内部返回?

时间:2020-07-09 10:47:02

标签: node.js express asynchronous

exports.postImportHomeworkAnnotations = async (req, res, next) =>{
    log.info("GOT REQUEST FOR IMPORT HOMEWORK ANNOTATIONS")
    
    const homework_id = req.body.homework_id;
    const pag = parseInt(req.body.page);
    const user = req.session.user;
    const userTaget = req.body.user_target;

    if(homework_id && pag ){
        let compito  = await CompitiModel.findById({_id : homework_id})
        .populate('risultati.risultati')

        if(compito.owner.user.toString() === user.objectId.toString()){
            for (let i = 0; i < compito.risultati.length; i++) {
                if(compito.risultati[i].risultati.owner.user.toString() === userTaget.toString() && compito.risultati[i].risultati.editable){

    
                    compito.risultati[i].risultati.blob_annotation.forEach(ele =>{
                        if(ele.page  === pag){
                            //WHEN I RETURN HERE
                            return res.json({data : ele.blob_annotation});
                        }
                    })
                    //EXECUTE EVEN THAT
                    return res.json({data : {}});
                }
            }
        }else{
            //......
           //..........
        }
    }
}

如何在第一次返回时正确返回并中断功能? 在该示例中,当我到达第一个返回时,代码将继续运行,甚至尝试使用res执行第二个返回,这会出错->错误:发送标头后无法设置标头。

0 个答案:

没有答案