Why do I not get the warning “a promise was created in a handler but was not returned from it”?

倖福魔咒の 提交于 2019-12-05 22:42:09

I will answer my own question because I found where the catch is.

Short answer: the problem is that warnings are printed in console only when this is enabled by configuration.

Explanation:

While searching on web I found this issue reported on Bluebird github. In the example code I saw that they manually updated Bluebird config using following code:

Promise.config({
    warnings: true,
    longStackTraces: true
});

I did the same before running my code:

Promise.config({
    warnings: true,
    longStackTraces: true
});

function getUser() {
    ...
}

function getUserData(userId) {
    ...
}

getUser().then(function(user) {
    getUserData(user);
}).then(function(userData) {
    // userData is undefined as expected
    console.log('Data: ', userData);
});

and output was finally with warning:

/usr/local/opt/node@6/bin/node test.js
get user
(node:96276) Warning: a promise was created in a handler at test.js:71:5 but was not returned from it, see <goo.gl link removed>
    at new Promise (node_modules/bluebird/js/release/promise.js:79:10)
Data:  undefined
get user data

Process finished with exit code 0

Checking further I also find that there is no need to manually set Bluebird configuration to see warnings in case if NODE_ENV variable is set to "development". In case of "development" such features are enabled automatically. This is also described in this API reference.

You need to write return inside then callback.

.then(function(data){return getusersata()})

And such way you need to return promise inside getuserdata

return new Promise

The problem is that an error was thrown and you don't have any .catch() method on your promise flow. You're example doesn't throw anything that's why you dont have any warning.

Try that and you'll see the warning :

getUser().then(function(user) {
    return getUserData(user);
}).then(function(userData) {
    // userData is undefined => now it is (you need to return previous Promise)
   throw new Error(); 
});

Here the warning will appear because of the error. But if you add .catch(console.error) it won't.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!