如何绕过多个然后进入猫鼬

时间:2017-04-29 11:41:20

标签: node.js mongodb mongoose promise

我不想将支票设为if (!isPresent)然后执行此操作....

当我的工作完成时,他们是否可以绕过所有然后

var isPresent=false;
    myPromise
            .then((employee) => {
                    if (employee) {
                        // throw 'employee already exist';
                        isPresent = true;
                        return res.data(mapper.toFullModel(employee));

                    }
                return model;
            });
            .then(model => {
                if (!isPresent) {
                    return new db.employee(model).save();
                }
            })
            .then(employee => {
                if (!isPresent) {
                    employee.token = auth.getToken(employee);
                    return employee.save();
                }
            })
            .then(employee => {
                if (!isPresent) {
                    res.data(mapper.toFullModel(employee));
                }
            })
            .catch(err => {
                res.failure(err);
            });

1 个答案:

答案 0 :(得分:0)

您可以重写您的保证链,以便它的第二部分嵌套:

myPromise.then(employee => {
  if (employee) {
    return res.data(mapper.toFullModel(employee));
  }
  return new db.employee(model).save().then(employee => {
    employee.token = auth.getToken(employee);
    return employee.save();
  }).then(employee => {
    return res.data(mapper.toFullModel(employee));
  });
}).catch(err => {
  res.failure(err);
});