【问题标题】:How to prevent Bluebird’s Warning: a promise was created in a handler but was not returned from it如何防止 Bluebird 的警告:在处理程序中创建了一个承诺,但没有从它返回
【发布时间】:2016-06-14 03:49:17
【问题描述】:

所以我有这个代码:

profileRepository.get(profileUuid).then((profile) => {
  if (profile.fileUuid) {
    profileStore.getFile(profile.fileUuid).then((fileData) => {
      data.fileData = fileData;
    }, callback);
  }

  data.profile = profile;
}, callback);

我收到警告:

Warning: a promise was created in a handler but was not returned from it

我相信这正在发生,因为profileStore.getFile() 也返回了一个承诺。现在通常摆脱该警告的方法是链接then(),做一些类似的事情:

profileRepository.get(profileUuid).then((profile) => {
  if (profile.fileUuid) {
    return profileStore.getFile(profile.fileUuid);
  }

  data.profile = profile;
}, callback)
.then((fileData) => {
  data.fileData = fileData;
}, callback);

问题是我必须有条件地调用profileStore.getFile(),所以我看不到在这种情况下如何使用 then 链接,也看不到以任何其他方式重写此代码以防止警告的方法从发生。我从get() 成功回调中尝试了return null,但这甚至不能阻止警告。

警告只是导致我的控制台日志被填满,当我需要进行调试和其他东西时真的很烦人,有没有办法在这个用例中防止这个警告?

更新

我也尝试过同样的警告:

profileRepository.get(profileUuid).then((profile) => {
  if (profile.fileUuid) {
    return profileStore.getFile(profile.fileUuid);
  }

  data.profile = profile;
}, callback)
.then((fileData) => {
  data.fileData = fileData;
}, callback);

【问题讨论】:

  • 简单,从它告诉你需要的地方返回一个承诺
  • 你对callback的用法看起来很奇怪。
  • @JarrodRoberson,我尝试了同样的警告(更新帖子)。
  • @robertklep 不知道你说的奇怪是什么意思,callback 是在任何承诺被拒绝时需要运行的。
  • 既然如此,何不使用.catch(callback)

标签: javascript promise bluebird


【解决方案1】:

问题是我必须有条件地调用 profileStore.getFile() 所以我看不出在这种情况下如何使用 then 链接

您不需要在这里使用链接。但是,如果您在 then 回调中执行异步操作,则始终需要 return 承诺,否则外部承诺不会等待它(而且您不希望这样)。

在您的情况下,您可以从回调中返回一个承诺,以便它等待data.fileData 被分配:

return profileRepository.get(profileUuid).then(profile => {
  data.profile = profile;
  if (profile.fileUuid)
    return profileStore.getFile(profile.fileUuid).then(fileData => {
      data.fileData = fileData;
    });
}).then(() => data, callback);

【讨论】:

    猜你喜欢
    • 2017-11-02
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多