Javascript mongoose的问题。保存承诺内永不返回 更新!!

Javascript mongoose的问题。保存承诺内永不返回 更新!!,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我在下面Dacre Denny answer的帮助下修复了我的初始问题,但是在为我的代码编写测试时,在服务器响应之前,更改没有被保存。我的测试数据库中的公司集合为空,我用以下代码修复了此问题 Companies.find({ company_name: company.company_name }).then(found => { if (found.length !== 0) { return res.status(400).json({ error: "Comp

我在下面Dacre Denny answer的帮助下修复了我的初始问题,但是在为我的代码编写测试时,在服务器响应之前,更改没有被保存。我的测试数据库中的公司集合为空,我用以下代码修复了此问题

  Companies.find({ company_name: company.company_name }).then(found => {
    if (found.length !== 0) {
      return res.status(400).json({ error: "Company already exists" });
    }

    var userForms = company.users;
    company.users = [];
    const finalCompany = new Companies(company);
    console.log(finalCompany);

    var userPromises = [];
    for (var x = 0; x < userForms.length; x++) {
      var user = userForms[x].user;
      user.company = finalCompany._id;
      userPromises.push(userCreation(user));
    }
    return Promise.all(userPromises).then(responses => {
      for (var x in responses) {
        if (!responses[x].errors) {
          finalCompany.addUser(responses[x]._id);
        } else {
          res.status(400).json(responses[x]);
        }
      }
      return finalCompany;
    });
  })
  // I moved the save in here !!!
  .then((finalCompany) => {
      finalCompany.save().then(()=>{
        res.status(200).json({signup:"Successful"});
      })
  },(err) => {
      res.json({error: err});
  });
});

这里有几个问题:

首先,
save()
函数是异步的。您需要通过确保将
save()
返回的承诺返回给调用它的处理程序来说明这一点

调用
Promise.all()
也是如此-您需要通过将该承诺返回到封闭的处理程序(请参见下面的注释)将该承诺添加到相应的承诺链中

另外,请确保请求处理程序通过
res.json()
res.send()
等方式返回响应,或者只需调用
res.end()
。这表明请求已经完成,应该解决“绞刑行为”

尽管您的代码包括
res.json()
,但在许多情况下,它不能保证被调用。在这种情况下,将导致悬挂行为。解决此问题的一种方法是将
res.end()
添加到承诺链的末尾,如下所示:

Companies.find({ company_name: company.company_name }).then(found => {
  if (found.length !== 0) {
    return res.status(400).json({ error: "Company already exists" });
  }

  var userForms = company.users;
  company.users = [];
  const finalCompany = new Companies(company);

  var userPromises = [];
  for (var x = 0; x < userForms.length; x++) {
    var user = userForms[x].user;
    user.company = finalCompany._id;
    userPromises.push(userCreation(user));
  }

  /* Add return, ensure that the enclosing then() only resolves
after "all promises" here have completed */
  return Promise.all(userPromises).then(responses => {
    for (var x in responses) {
      if (!responses[x].errors) {
        finalCompany.addUser(responses[x]._id);
      } else {
        res.status(400).json(responses[x]);
      }
    }
    console.log("h2");

    /* Add return, ensure that the enclosing then() only resolves
    after the asnyc "save" has completed */
    return finalCompany.save(function() {
      console.log("h3");
      return res.status(200);
    });
  });
})
.then(() => {
    res.end();
},(err) => {
    console.error("Error:",err);
    res.end();
});
companys.find({company\u name:company.company\u name})。然后(find=>{
如果(找到.长度!==0){
返回res.status(400).json({error:“公司已经存在”});
}
var userForms=company.users;
company.users=[];
const finalCompany=新公司(公司);
var userpromissions=[];
for(var x=0;x{
对于(响应中的var x){
如果(!响应[x]。错误){
finalCompany.addUser(响应[x]。\u id);
}否则{
res.status(400).json(responses[x]);
}
}
控制台日志(“h2”);
/*添加return,确保封闭的then()只解析
asnyc“保存”完成后*/
返回finalCompany.save(函数(){
控制台日志(“h3”);
返回res.status(200);
});
});
})
.然后(()=>{
res.end();
},(错误)=>{
console.error(“error:,err”);
res.end();
});

嘿,我已经更新了我的代码,它工作得很好,但是在我尝试为我的API编写一些测试后了解到的响应之后,保存才完成。有没有办法强迫保存回调在上次回调的res.end之前发生?不用担心,修复了这个问题,并更新了我的原始帖子以反映它,再次感谢。很抱歉耽误了你的回复。现在请阅读你的留言。如果还有什么需要我帮忙的,请告诉我
h2
h3
Companies.find({ company_name: company.company_name }).then(found => {
  if (found.length !== 0) {
    return res.status(400).json({ error: "Company already exists" });
  }

  var userForms = company.users;
  company.users = [];
  const finalCompany = new Companies(company);

  var userPromises = [];
  for (var x = 0; x < userForms.length; x++) {
    var user = userForms[x].user;
    user.company = finalCompany._id;
    userPromises.push(userCreation(user));
  }

  /* Add return, ensure that the enclosing then() only resolves
after "all promises" here have completed */
  return Promise.all(userPromises).then(responses => {
    for (var x in responses) {
      if (!responses[x].errors) {
        finalCompany.addUser(responses[x]._id);
      } else {
        res.status(400).json(responses[x]);
      }
    }
    console.log("h2");

    /* Add return, ensure that the enclosing then() only resolves
    after the asnyc "save" has completed */
    return finalCompany.save(function() {
      console.log("h3");
      return res.status(200);
    });
  });
})
.then(() => {
    res.end();
},(err) => {
    console.error("Error:",err);
    res.end();
});