我的代码如下:(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()
执行后台作业,因此不需要返回 promise 。但是由于它创建了一个 promise ,当函数在 then()
中被调用时,在 then()
中没有显式的 return null
, bluebird 将以下警告打印到控制台。 “警告:在处理程序中创建了 promise ,但未从中返回”。
这有点不公平,因为调用者不需要知道函数使用了 promise。如何让 bluebird 在调用者的 then()
中不使用 return null
来忽略警告?
我不想禁用警告,因为它非常有用。
最佳答案
一种可能性是添加后台 .then
separately,并只返回基本 promise :
function test() {
const prom = promised();
prom.then(doBackgroundJob);
return prom;
}
同时让 doBackgroundJob
返回 promise (在这个实现中 继续被丢弃):
function doBackgroundJob() {
// this is an intentional runaway promise.
return backgroundJob()
.catch(function(err) {
console.log('error', err);
});
}
允许 doBackgroundJob
的其他消费者在需要时使用它返回的 promise 。
关于javascript - Bluebird promise : How to avoid the runaway promise warning in a nested function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50343036/