Maximilian Lloyd Maximilian Lloyd - 6 months ago 95
Node.js Question

(node:5540) Warning: a promise was created in a handler but was not returned from it

The following code:

function handleError(res, statusCode) {
statusCode = statusCode || 500;
return function(err) {
res.status(statusCode).send(err);
};
}

function respondWithResult(res, statusCode) {
statusCode = statusCode || 200;
return function(entity) {
if (entity) {
res.status(statusCode).json(entity);
}
};
}


// Creates a new Store in the DB
export function create(req, res) {
// create user
let user = req.body.user;
let store = req.body.store;

auth.hash(user.password)
.then(hash => {
user.password = hash;
// Create user, then create store, attach store object id to user, and attach user object id to store
User.create(user)
.then(userRes => {
store.owner = userRes._id;
store.memebers = [];
store.memebers.push(store.owner);

Store.create(store)
.then(storeRes => {
return respondWithResult(res, 201);
})
.catch(err => handleError(err));
})
.catch(err => handleError(err));
})
.catch(err => handleError(err));
}


prints the error mentioned in the title, "(node:5540) Warning: a promise was created in a handler but was not returned from it". I have tried changing and tweaking the code but the error still persists.

Answer

This warning is because your code is creating promises inside of .then() handlers, but not returning them from those handlers.

Change:

User.create(user)

to:

return User.create(user)

And, change:

Store.create(store)

to

return Store.create(store)

When you don't return these promises that are created inside .then() handlers, they become separate, independent promise chains and are not linked to the previous promise chain. This is usually a programming mistake which is why Bluebird makes it a warning.

When you return them, then they add to the promise chain and thus the parent promise waits for their completion before continuing on with the chain.


I'd also suggest you probably want to change:

auth.hash(user.password)

to:

return auth.hash(user.password)

So that the caller of create() can tell when everything is done.


And, you only need one .catch() handler at the highest level. Rejected promises propagate up to the top level for you automatically (one of the things that makes error handling when using promises easier).