I call storage.createTask and use BlueBird's promises to get the returned value. This works fine when I do new Promise()
and resolve the promise using either resolve(something)
or reject(error)
. However, Promise.reject(new Error('some error'))
causes cannot read property 'then' of undefined
.
According to the docs, Promise.reject
Creates a promise that is rejected with the given reason
. Isn't this similar to reject(error)
, which works fine?
What's the difference between Promise.resolve/Promise.reject
and doing new Promise
? When should we use one over the other?
//server.js
// returning Promise.reject causes
// Cannot read property 'then' of undefined
storage.createTask(task).then(function(id) {
task.id = id;
reply(task);
}, function(error) {
console.log(error);
reply(error);
});
// storage.js
function _create(task) {
return new Promise(function(resolve, reject) {
var id = shortid.generate();
Task.create({
id: id,
content: task.content,
deadline: task.deadline,
milestone_id: task.milestone_id,
}).catch(function (error) {
reject(error); // works ok
}).then(function() {
resolve(id); //works ok
});
});
}
module.exports = {
createTask: function(task) {
if (task.milestone_id != null ) {
Milestone.isExist(task.milestone_id).then(function(exists) {
if (!exists) {
return Promise.reject(new Error('some error'));
}
return _create(task);
});
} else {
return _create(task);
}
}