【问题标题】:How to Jump Back and forth in if/else block in mongoose function?如何在猫鼬函数的 if/else 块中来回跳转?
【发布时间】:2018-07-05 19:53:54
【问题描述】:

如何在mongoose函数的if/else块中来回跳转?
我的意思是当我的用户已经存在时,然后检查是否阻止,如果我的用户在 db 中不存在,则转到 else 阻止并保存用户,然后返回 if 块,我不想将 if 块复制并粘贴到else 保存用户后屏蔽

代码:

User.findById(msg.chat.id)
  .then((doc) => {
    if (doc) {
      console.log(doc.name);  // to here
    } else {
      console.log('Empty');  //jump from here
    }
  }).catch((err) => {
    if (err) {
      console.log(err);
    }
  });

【问题讨论】:

  • 只需将公共部分从if/else 块中取出即可。
  • 你能用我的例子编辑吗? ,我的意思是我想将用户保存在 else 块中并返回到 if
  • 嗯,这是一个完全不同的问题。我建议您编辑您的示例,因为我和@FirasOmrane 都没有理解其他内容。
  • 您应该真正编辑您的代码示例,因为它非常令人困惑,并且对您提出的实际问题没有任何帮助。

标签: javascript node.js if-statement mongoose promise


【解决方案1】:

你的意思是这样!!

当使用回调时,我们保证文档在使用时被保存。

与方法保存一起使用的回调接收three parameters

  function workAfterSaving(result) {
    console.log(result.tok);
  }

  User.findById(msg.chat.id)
    .then((doc) => {
      if (!doc) {
        // we will add the user
        kitty.save()
          .then((obj) => {
            workAfterSaving(obj);
          }).catch((err) => {
            if (err) {
              console.log(err);
            }
          });
        return;
      }

      // here we will use the same function with the found user.
      workAfterSaving(doc);
    }).catch((err) => {
      if (err) {
        console.log(err);
      }
    });
});

【讨论】:

  • 在阅读 OP 的评论后,我认为他们实际上想在 else 块中完成某些操作后重新运行 findById,这实际上并不仅仅是在做 console.log 的事情。
  • 我的意思是当我的用户已经存在时,检查是否阻止,如果我的用户不在 db 中,则转到 else 阻止并保存用户,然后返回 if,我不想保存用户后复制粘贴 if 块到 else 块
  • @SedricHeidarizarei 我修改了它以满足您的要求
  • //here you can code what you want to do with every user 他们必须再次findById,您的示例没有解释如何做,而是问题的重点。
  • @SedricHeidarizarei 我修改了代码,使其更加开发和解释。不客气。
猜你喜欢
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 2018-07-30
  • 2021-05-24
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多