JavaScript/node.js在另一个诺言中返回承诺



我对那些承诺的事情有点混淆,不明白为什么我不能将诺言归还给另一个承诺。我的问题是以下内容,我有一个函数保存:

save(Driver) {
    this.exists(Driver).then(exist => {
        if(exist) {
            return new Promise(function (resolve, reject) {
                if (exist === true) {
                    resolve(true);
                } else if (exist === false) {
                    resolve(false);
                } else {
                    reject(err);
                }
            });
        }
    });
};

很容易,当我尝试将该功能称为以下时:

save(driver).then(this.common.saveSuccess(res))
            .catch(this.common.noSuccess(res));

我遇到了一个错误,说Cannot read property 'then' of undefined,我不明白为什么要回报承诺。感谢您的帮助

您的save功能非常复杂。您在这里不需要嵌套承诺,只需从this.exists函数返回结果(承诺):

save(Driver) {
  return this.exists(Driver);
};

另外,您不正确地使用此功能。save函数可以使用truefalse值解决,因此您需要在then回调中验证此值并使用catch回调可能发生的错误:

save(driver)
  .then(exists => {
    if (exists) {
      this.common.saveSuccess(res);
    } else {
      this.common.noSuccess(res)
    }
  })
  .catch(err => // process error here);

最新更新