如何在mongoose函数中的if / else块中来回跳转?

时间:2018-01-26 13:06:57

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

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

代码:

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);
    }
  });

1 个答案:

答案 0 :(得分:1)

你的意思是这样!!

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

方法save使用的回调接收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);
      }
    });
});