Javascript 如何使快速路线在向客户发回响应之前做两件事?

Javascript 如何使快速路线在向客户发回响应之前做两件事?,javascript,express,es6-promise,Javascript,Express,Es6 Promise,我试图在快速路线中完成各种事情,简而言之,我有这个路线/checkNsguid,在这里我提交了一个表单。我希望路线能做到以下几点: 验证nguid代码是否有效(它存在于数据库中) 如果找到有效的nguid代码,它会将nguid表中的一些字段复制到模型表(它会更新模型对象) 它将udpated模型对象发送回客户端应用程序 出于某种原因,我仍在取回旧型号的obj。我可以看到它在db上用有效字段进行了更新,但是res.send(…)仍然向我发送旧的obj 我不知道这是我使用的Promises、使用ne

我试图在
快速路线中完成各种事情,简而言之,我有这个路线
/checkNsguid
,在这里我提交了一个表单。我希望路线能做到以下几点:

  • 验证
    nguid
    代码是否有效(它存在于数据库中)
  • 如果找到有效的
    nguid代码
    ,它会将
    nguid表
    中的一些字段复制到
    模型表
    (它会更新模型对象)
  • 它将udpated模型对象发送回客户端应用程序
  • 出于某种原因,我仍在取回旧型号的obj。我可以看到它在
    db
    上用有效字段进行了更新,但是
    res.send(…)
    仍然向我发送旧的obj

    我不知道这是我使用的
    Promises
    、使用
    next()
    的方式还是我缺少的其他方式。如果有人能给我指出正确的方向,请

    谢谢

    /**
    *检查列表中是否有nguidCode
    *
    *@return{JSON}
    */
    转发器(
    “/checkNguid”,
    (请求、恢复、下一步)=>{
    让modelID=req.body.modelID
    设nguid=req.body.nguid
    //1.步骤1
    //转到CheckNGUID表
    //映射所有集合,直到找到一个匹配的集合
    //提交的代码
    //验证代码是否有效,如果有效,则复制各种
    //通过“.UpdateInfo-FromoldDB”将字段添加到ModelTable`
    //在那之后,我不想再和那个回复obj有任何关系了。
    //我想“传递”控制到步骤2
    nguidCode
    .checkNguid(nguid)
    。然后((响应)=>{
    log('这是后端内部的响应',响应)
    response.length==0
    ?res.status(400).json({result:'nok',error:'Invalid nguidCode'})
    :response.map((el)=>
    //[注意]:如果找到,则使用nguid信息更新模型对象
    modelModel.updateInfosFromOldDb(
    modelID,
    恩古德,
    el.rate,
    el.subscribedAt,
    ),
    )
    下一个()
    //log('这是后端2'内的响应,响应)
    //json({result:'ok',model:response})
    //json({result:'ok',model:response})
    })
    .catch((错误)=>{
    res.status(400).json({result:'nok',Error:Error.toString()})
    })
    },
    //2.步骤2
    //这是我想发送回客户端应用程序的更新模型obj。
    //[询问]:我想发回更新的模型对象,
    //不过我还是要把旧的拿回来。
    (请求、回复)=>{
    modelModel.getByID(req.body.modelID).then((响应)=>{
    log('下一个()中的响应',响应)
    json({result:'ok',model:response})
    })
    },
    )
    

    updateInfosFromOldDb

    const updateInfosFromOldDb = (modelID, nguid, rate, subscribedAt) => {
    
      return new Promise((resolve, reject) => {
        ModelModel.findOne({ id: modelID }, (err, model) => {
          if (err) {
            reject(err);
          }
          model.nguidCode= nguid
          model.rate= rate
          model.subscribedAt =subscribedAt
          //model.payments.push(paymentId);
    
          model.save((err, response) => {
            if (err) {
              reject(err)
            } else {
              resolve(response)
            }
          })
        })
        
      });
    
    }
    

    由于在
    nguidCode.checkNguid
    promise之前调用了
    next()
    ,因此您得到的是旧的响应。即,在数据库调用完成之前,checkNguid
    promise将解析。为了解决这个问题,我们需要在
    then()
    块中移动
    next()
    -

    /**
     * Check if nguidCode is in the list
     *
     * @return {JSON}
     */
    router.post(
      '/checkNguid',
      (req, res, next) => {
        let modelID = req.body.modelID
        let nguid = req.body.nguid
    
        // console.log(req.body, 'req.body in the backend')
    
        nguidCode
          .checkNguid(nguid)
          .then((response) => {
            console.log('this is the response inside backend', response)
            if(response.length === 0) {
              throw new Error('Invalid nguidCode');
            } else {
              // Wrapping list of promises in Promise.all so that then() callback is invoked once all
              // promises are resolved
              return Promise.all(response.map((el) =>
              // [NOTE]: Updates the model object with the nguid info if found
                modelModel.updateInfosFromOldDb(
                  modelID,
                  nguid,
                  el.rate,
                  el.subscribedAt,
                ),
              ))
            }
            // console.log('this is the response inside backend 2', response)
            // res.status(200).json({ result: 'ok', model: response })
            // res.status(200).json({ result: 'ok', model: response })
          })
          .then((data) => {
            return next()
          })
          .catch((error) => {
            return res.status(400).json({ result: 'nok', Error: error.toString() })
          })
        // [NOTE]: This also works I go onto the modelModel.getByID(...)
      },
    
      // [ASK]: I want to send back the updated model Object,
      // However I'm still getting back the old one.
      (req, res) => {
        modelModel.getByID(req.body.modelID).then((response) => {
          console.log('response inside the next()', response)
          return res.status(200).json({ result: 'ok', model: response })
        })
      },
    )
    

    如您所述移动了
    next()
    ,但仍然存在相同的问题。在调用
    next()
    之前,是否可以记录
    响应
    对象?我不知道为什么会在那个里使用map,它不会更新响应对象,但会从中创建新的数组。另外,
    updateInfo-FromoldDB
    是一个异步函数吗?
    updateInfo-FromoldDB
    也是一个异步函数。刚刚用更多信息编辑了我的答案OK,map不会等待异步函数完成。将更新答案以处理它。感谢您解决了问题,如果我理解正确的话。您将所有内容包装在一个
    Promise.all()
    中,以等待承诺完成,然后调用
    next()