【问题标题】:Bluebird promise: How to avoid the runaway promise warning in a nested function?蓝鸟承诺:如何避免嵌套函数中的失控承诺警告?
【发布时间】:2018-05-15 16:58:43
【问题描述】:

我的代码如下:(node.js代码)

'use strict';

var Promise = require('bluebird');

function promised()
{
    return Promise.resolve();
}

function backgroundJob()
{
    return Promise.resolve();
}

function doBackgroundJob()
{
    // this is an intentional runaway promise.
    backgroundJob()
    .catch(function (err)
    {
        console.log('error', err);
    });
}

function test()
{
    return promised()
    .then(function ()
    {
        doBackgroundJob();
        return null;  // without this, bluebird displays the warning
    });
}

doBackgroundJob() 做一个后台工作,所以它不需要返回一个承诺。但由于它创建了一个承诺,当在 then() 中调用该函数时,在 then() 中没有明确的 return null 时,bluebird 会向控制台打印以下警告。 '警告:在处理程序中创建了一个承诺,但没有从它返回'。

这有点不公平,因为调用者不需要知道函数使用了 Promise。如何让蓝鸟忽略调用者中then() 中没有return null 的警告?

我不想禁用警告,因为它非常有用。

【问题讨论】:

  • 您可以在 bluebird 中禁用一般警告:bluebirdjs.com/docs/api/promise.config.html
  • @Thomas 谢谢,但我不想禁用警告。我已经更新了问题。
  • “如何让 bluebird 忽略警告”“我不想禁用警告,因为它非常有用。” i> 我很困惑。
  • @Thomas 我只想忽略这种情况下的警告。该警告通常非常有用。
  • promised().then(function(){ setTimeout(doBackgroundJob) }); 我认为您不会介意这里的这几毫秒延迟。另一方面,return null 有什么问题?

标签: javascript promise bluebird


【解决方案1】:

一种可能性是添加背景.then单独,并且只返回基本承诺:

function test() {
  const prom = promised();
  prom.then(doBackgroundJob);
  return prom;
}

虽然让doBackgroundJob 返回承诺(在此实现中继续被丢弃):

function doBackgroundJob() {
  // this is an intentional runaway promise.
  return backgroundJob()
    .catch(function(err) {
      console.log('error', err);
    });
}

允许doBackgroundJob 的其他消费者在需要时使用它返回的承诺。

【讨论】:

    【解决方案2】:

    这取决于:

    • doBackgroundJob 正在做一些异步的事情,所以它应该像往常一样返回一个承诺,让调用者知道它什么时候完成。即使它已经完成了所有错误处理并保证只履行承诺。调用者知道它返回了一个承诺,将在then 回调中使用return null 来避免警告。

      function doBackgroundJob() {
        return backgroundJob().catch(console.error);
      }
      
    • 如果调用者不知道 doBackgroundJobb 在做什么,您可以异步创建承诺(这样 Bluebird 不会注意到)并且什么都不返回(这样调用者不会注意到):

      function doBackgroundJob() {
        process.nextTick(() => {
          // this is an intentional runaway promise.
          backgroundJob().catch(console.error);
        });
      }
      

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 2014-08-16
      • 2023-03-31
      • 2019-03-04
      相关资源
      最近更新 更多