Promise 链和条件

Promise chaining and conditionals

很确定我可以用 async/await 做到这一点,但我想了解如何在没有

的情况下实现这个逻辑

工作流程:

代码:

    Job.findByPk(jobId)
       .then(job => {
           if(job) return Person.findOne(...)
           else res.status(404).json(...)
       })
       .then(person => {
           if(person)
               // Do person logic here
       })
       .catch(err => ...);

问题是这个逻辑显然行不通。如果找不到工作 没有人,则第二个 .then() 块中的 person 参数可能未定义。

所以解决方案是在第一个 .then() 块中执行此操作:

       .then(job => {
           if(job) // store the job locally
           else res.status(404).json(...)

           return Person.findOne(...)
       })

但这意味着无论是否找到工作都会搜索数据库,而不是以找到工作为条件

如何以更有意义的方式构建它?

谢谢

使用 await 就简单多了(假设你把父函数设为 async):

try {
    const job = await Job.findByPk(jobId);
    if (!job) {
         return res.status(404).json(...)
    }
    const person = await Person.findOne(...);
    if (person) {
        ...
    } else {
        ...
    }
} catch(e) {
    console.log(e);
    res.sendStatus(500);
}

让这个流程变得如此简单的原因是所有变量都在同一个范围内,你可以 return 在你想要完成流程的任何地方。

如果您要坚持之前的 .then() 逻辑,请参阅此答案: 多个不同的选项。

您只需在前 .then 内添加 .then

Job.findByPk(jobId)
  .then(job => {
    if(job)
      return Person.findOne(...)
        .then(person => {
          if(person)
          // Do person logic here
        });
    else res.status(404).json(...)
  })
  .catch(err => ...);

选择的答案是实现我想要的东西的最佳方式 - 即仅使用 async/await - 但对于任何想知道我如何坚持链接的人来说,它只是正确地打破它。我最终通过抛出一个错误(然后在别处处理)

       .then(job => {
           if(!job) {
              const error = new Error('Job not found');
              error.statusCode(404);
              throw error;
           } else  {
              return Person.findOne(...)
           }

       })
       .then(person => { // Person logic })
       .catch(err => next(err))