Bluebird promises - nesting vs rejecting pattern - javascript

I'm working on an app for which we're using promises. I'm attempting to figure out what the better pattern is.
Breaking up concerns between thenables and rejecting the promise if an error. Rejection is then handled in a catch block. Or is it better to throw a new type of error and handle in the catch block?
Account.findOneAsync({email: request.payload.email})
.then(function (user) {
if (user) {
return user.compareHash(request.payload.password);
} else {
// Account not found
return Bpromise.reject('AccountNotFound');
}
})
.then(function (validPassword) {
if (validPassword) {
return request.auth.jwt.user.sign();
} else {
// Invalid password
return Bpromise.reject('InvalidPassword');
}
})
.then(function (jwt) {
var response = reply.success();
return response.header('authorization', jwt);
})
.catch(function (e) {
if (e === 'AccountNotFound' || e === 'Invalid Password') {
return reply(Boom.unauthorized('Invalid username/password'));
} else {
// Perhaps log something like unhandled error
return reply(Boom.unauthorized('Invalid username/password'));
}
});
Or nesting promising as such. I feel here that this is just going down the same rabbit hole of "callback hell" though.
Account.findOneAsync({email: request.payload.email})
.then(function (user) {
if (user) {
user.compareHash(request.payload.password)
.then(function (valid) {
if (valid) {
request.server.plugins.jwt.sign()
.then(function (jwt) {
var response = reply.success();
return response.header('authorization', jwt);
});
} else {
// Invalid password
return reply(Boom.unauthorized('Invalid username/password'));
}
});
} else {
// Account not found
return reply(Boom.unauthorized('Invalid username/password'));
}
})
.catch(function (e) {
console.log(e);
});

I think you can get the best of both worlds by throwing and then catching your boom objects.
One thing you're missing in both approaches is that when you're already inside a then handler, the idiomatic thing to do is throw an error rather than creating and returning a rejected promise. You also don't need an else block after a return statement:
Account.findOneAsync({email: request.payload.email})
.then(function (user) {
if (user) {
return user.compareHash(request.payload.password);
}
// Account not found
throw Boom.unauthorized('Invalid username/password');
})
.then(function (validPassword) {
if (validPassword) {
return request.auth.jwt.user.sign();
}
// Invalid password
throw Boom.unauthorized('Invalid username/password');
})
.then(function (jwt) {
var response = reply.success();
return response.header('authorization', jwt);
})
.catch(function (e) {
if (e.isBoom) {
return reply(e);
}
// Perhaps log something like unhandled error
return reply(Boom.unauthorized('Invalid username/password'));
});

Related

How can return false value promise method in node if array is empty and vise versa

i was trying out promise code but it always returns me resolve even if the user does not exist in the database
can anyone help me fix my code and the return statement
in the return function the the second console log is only working.
here is my code
Api Call
const email = 't#t.com';
const request = require('request');
function IsUserExists(email, kc_accessToken) {
let url = `${path}/users?email=${email}`;
return new Promise(function (resolve, reject) {
request(
{
url: url,
headers: {
'content-type': 'application/json',
authorization: `Bearer ${kc_accessToken}`,
},
},
function (error, response, body) {
if (error) {
console.log('some error occured');
}
if (response.body.length > 0) {
console.log('User Exist');
return resolve();
}
console.log('Does not Exist');
return reject();
}
);
});
}
Function Call
http
.createServer(function Test() {
getAccessToken()
.then(function (response) {
kc_accessToken = response.data.access_token;
IsUserExists(email, kc_accessToken).then((resp) => {
if (resp) {
console.log('Do Not Create');
} else if (!resp) {
console.log('Creat a new User');
}
});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
})
.listen(8081);
When Provided user email which exist ( t#t.com )
When Provided user email which does not exist( 09#t.com )
I need to create a new answer for example to you question in comments.
Now, you go into the reject function so you need to handle this rejection in the outside.
if (response.body.length > 0) {
console.log('User Exist');
return resolve();
}
console.log('Does not Exist');
return reject(); // -> Now here you are
You need add .catch function after IsUserExists.then().
It will be IsUserExists.then().catch()
http.createServer(function Test() {
getAccessToken()
.then(function (response) {
kc_accessToken = response.data.access_token;
// here you only accept the data from resolve in Promise
// so you need to add .catch function to handle the rejection.
IsUserExists(email, kc_accessToken).then((resp) => {
if (resp) {
console.log('Do Not Create');
} else if (!resp) {
console.log('Creat a new User');
}
}).catch((error) => {
console.log(error)
});
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
})
.listen(8081);
By the way, you could add parameter in rejection function like reject(new Error("user not found)).
Then in the outside, you can get this rejection message.

How to break out of a promise (.then) statement javascript

I'm having a problem trying to break out of a promise statement when an error occurs in a catch statement.
I'm not sure if I can throw an error inside a catch statement.
The problem: The catch function isn't doing anything when I throw an error.
Expected result: For the catch statement to display an alert and break the promise chain.
The code:
if (IsEmail(email)) {
$('body').loadingModal({
position: 'auto',
text: 'Signing you in, please wait...',
color: '#fff',
opacity: '0.9',
backgroundColor: 'rgb(0,0,0)',
animation: 'doubleBounce'
});
var delay = function(ms){ return new Promise(function(r) { setTimeout(r, ms) }) };
var time = 2000;
delay(time)
.then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
.then(function() {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function () {
var user = firebase.auth().currentUser;
uid = user.uid;
configure();
})
.catch(function(error) {
throw error;
});
})
.then(function() { $('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange'); return delay(time); } )
.then(function() { $('body').loadingModal('hide'); return delay(time); } )
.then(function() { $('body').loadingModal('destroy') ;} )
.catch(function(error) {
alert("Database error: " + error);
});
}
else {
alert("Please enter a valid email");
return;
}
The second .then after the delay resolves immediately, because nothing is being returned from it. Return the signInWithEmailAndPassword call instead, because it returns a Promise that you need to chain together with the outer Promise chain:
.then(function() {
return firebase.auth().signInWithEmailAndPassword(email, password)
// ...
Also, catching and immediately throwing doesn't really do anything - unless you need to handle an error particular to signInWithEmailAndPassword there, feel free to omit that catch entirely:
delay(time)
.then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
.then(function() {
return firebase.auth().signInWithEmailAndPassword(email, password)
})
.then(function () {
var user = firebase.auth().currentUser;
uid = user.uid;
configure(); // if configure returns a Promise, return this call from the `.then`
})
.then(
// ...
.catch(function(error) {
alert("Database error: " + error);
});
If configure returns a Promise as well, then you need to return it too. (if it's synchronous, there's no need)
(you might also consider using a more user-friendly way of displaying the error, perhaps use a proper modal instead of alert)
Another option to consider is using await instead of all these .thens, the control flow may be clearer:
(async () => {
if (!IsEmail(email)) {
alert("Please enter a valid email");
return;
}
$('body').loadingModal({
position: 'auto',
text: 'Signing you in, please wait...',
color: '#fff',
opacity: '0.9',
backgroundColor: 'rgb(0,0,0)',
animation: 'doubleBounce'
});
var delay = function(ms) {
return new Promise(function(r) {
setTimeout(r, ms)
})
};
var time = 2000;
try {
await delay(time);
$('body').loadingModal('animation', 'foldingCube');
await delay(time);
await firebase.auth().signInWithEmailAndPassword(email, password)
var user = firebase.auth().currentUser;
uid = user.uid;
configure(); // if this returns a Promise, `await` it
$('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange');
await delay(time);
$('body').loadingModal('hide');
await delay(time);
$('body').loadingModal('destroy');
} catch(error) {
alert("Database error: " + error);
}
})();

function returns a promise reject when resolved

I have a angularjs controller and factory.
So my purpose is to manage all the message errors depending of the promise result. That means to receive in the controller a reject after checking some bad values in the resolve factory function.
I'm trying this way but it doesn't work:
factory.js
var mediaRecent;
function getMediaByUserName(user) {
return $http.get('https://www.instagram.com/' + user + '/media')
.then(function (response) {
if (response.data.items.length === 0) {
// I want here to cause a reject in the controller function
return new Error('This user is not public');
}
mediaRecent = response.data.items;
})
.catch(function (error) {
return new Error('There was a problem looking to that user');
});
}
controller.js
instagramFactory.getMediaByUserName(vm.name)
.then(function () {
$state.go('instagramMediaRecent');
})
.catch(function (error) {
vm.error = error.message;
});
var mediaRecent;
function getMediaByUserName(user) {
return $http.get('https://www.instagram.com/' + user + '/media')
.then(function (response) {
if (response.data.items.length === 0) {
// go to catch() from here
return $q.reject(new Error('This user is not public'));
}
mediaRecent = response.data.items;
})
.catch(function (error) {
return new Error('There was a problem looking to that user');
});
}
Actually you called promise twice. So you can call it only in Controller or Factory.
Simple way
Factory:
function getMediaByUserName(user) {
return $http.get('https://www.instagram.com/' + user + '/media');
}
Controller:
instagramFactory.getMediaByUserName(vm.name)
.then(function () {
if (response.data.items.length === 0) {
// I want here to cause a reject in the controller function
return new Error('This user is not public');
}
var mediaRecent = response.data.items;
$state.go('instagramMediaRecent');
})
.catch(function (error) {
vm.error = new Error('There was a problem looking to that user');
});

Unhandled promise rejection Error: Can't set headers after they are sent

I would like to make a if else return (for conrtole) but: "UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Can't set headers after they are sent.
"
exports.delete = function (req, res) {
Parking.findById(req.params.id).exec()
.then(function (parking) {
if (userController.ensureAuthorized(req, 'Director', parking.id)) {
return parking;
}
return res.status(403).send({msg: 'unauthorized'});
})
.then(function (parking) {
User.update().exec();
return parking;
})
.then(function (parking) {
return Parking.remove({_id: parking._id}).exec();
})
.then(function () {
res.status(200).json({msg: 'Ok ! Parkink remove'});
})
.catch(function (err) {
return res.status(400).send(err);
});
};
Ty
The issue is that after return res.status(403), the promise chain doesn't stop automagically. Eventually, it will hit res.status(200) and cause the error.
You can rewrite your promise chain a bit to prevent this. I'm not sure what the purpose of that User.update().exec() is, but I assume that you wanted to call it and also wait for its promise to get resolved before continuing:
exports.delete = function (req, res) {
Parking.findById(req.params.id).exec()
.then(function (parking) {
if (userController.ensureAuthorized(req, 'Director', parking.id)) {
return User.update(...).exec().then(function() {
return Parking.remove({_id: parking._id}).exec();
}).then(function() {
return res.status(200).json({msg: 'Ok ! Parkink remove'});
});
} else {
return res.status(403).send({msg: 'unauthorized'});
}
}).catch(function (err) {
return res.status(400).send(err);
});
};
Well there is no standard way of breaking the promise chain.
So I am going to throw an error to break the chain, and then handle that custom thrown error:
exports.delete = function (req, res) {
Parking.findById(req.params.id).exec()
.then(function (parking) {
if (userController.ensureAuthorized(req, 'Director', parking.id)) {
return parking;
}
else {
res.status(403).send({msg: 'unauthorized'});
throw new Error('BREAK_CHAIN'); // <-- intentionally throw error
}
})
.then(function (parking) {
User.update().exec();
return parking;
})
.then(function (parking) {
return Parking.remove({_id: parking._id}).exec();
})
.then(function () {
res.status(200).json({msg: 'Ok ! Parkink remove'});
})
.catch(function (err) {
if(err.message != 'BREAK_CHAIN') // <-- handle if error was intentionally thrown
return res.status(400).send(err);
});
};
just as an addition to the other answers given, I would recommend:
1) breaking things up into small parts
2) using throw as intended, to raise the error of non-authorization
function update (parking) {
User.update().exec()
.then(function () {
Parking.remove({_id: parking._id}).exec();
});
}
exports.delete = function (req, res) {
// auth needs req so we put it in scope
var auth = function (parking) {
if (!userController.ensureAuthorized(req, 'Director', parking.id)) {
throw(new Error(403));
}
return parking;
}
Parking.findById(req.params.id).exec()
.then(auth)
.then(update)
.then(function () {
res.status(200).json({msg: 'Ok ! Parkink remove'});
})
.catch(function (err) {
if (err.message === 403) {
return res.status(403).send({msg: 'unauthorized'});
}
return res.status(400).send(err);
});
};

Static Promise.resolve()/reject() is always interpreted as resolve()

I'm using the following two pieces of code :
Store.addUser(newUserInfo).then(function(firstResult) {
Store.getUserList().then(function(result){
console.log('this side');
console.log(result);
io.sockets.emit('userAdded', {
userMapByUserId: result
});
}, function(error) {
console.log('List of users could not be retrieved');
console.log(error);
io.sockets.emit('userAdded', {
userMapByUserId: []
});
}
);
}, function(rejection) {
socket.emit('userNotAdded', {
userId: -1,
message: rejection.reason,
infoWithBadInput: rejection.infoWithBadInput
});
});
and in Store :
var addUser = function(newUserInfo) {
var validationResult = Common._validateUserInfo(newUserInfo);
if (validationResult.isOK) {
return keyValueExists('userName', newUserInfo.userName).then(function(userNameAlreadyExists) {
if (userNameAlreadyExists) {
validationResult = {
isOK: false,
reason: 'Username already exists',
infoWithBadInput: 'userName'
};
return Promise.reject(validationResult);
} else {
var newUserId = generateUserId();
//TODO: change it somehting more flexible. e.g. a predefined list of attributes to iterate over
var newUser = {
'userName': newUserInfo.userName,
'password': newUserInfo.password,
'userId': newUserId,
'lastModificationTime': Common.getCurrentFormanttedTime(),
'createdTime': Common.getCurrentFormanttedTime()
};
var user = new User(newUser);
user.save(function(err) {
if (err) {
console.log(err);
console.log('There is a problem saving the user info');
return Promise.reject('There is a problem saving the user info');
} else {
console.log('A new user added: ');
console.log(newUser);
//return getUserList();
return Promise.accept(newUser);
}
});
}
});
} else {
return Promise.reject(validationResult);
}
};
But in the first code , when I do Store.addUser(newUserInfo) it always runs the first function (resolve function) which shouldn't be the case if we do return Promise.reject() in addUser. Any idea on why this happens ?
You've got two return statements too few, two too much, and are overlooking a non-promisified function call.
Store.addUser(newUserInfo).then(function(firstResult) {
return Store.getUserList().then(function(result){
// ^^^^^^
…
This one is not really problematic, as you don't chain anything after the resulting promise, but it shouldn't be missed anyway.
…
return keyValueExists('userName', newUserInfo.userName).then(function(userNameAlreadyExists) {
if (userNameAlreadyExists) {
…
} else {
…
var user = new User(newUser);
user.save(function(err) { … });
// ^^^^
}
});
In this then-callback, you are not returning anything from your else branch. The promise is immediately fulfilled with undefined, and the ongoing save call is ignored - your promises don't know about it, so they can't await it. That's why Store.getUserList() that follows next in the chain doesn't see the changes; they're not yet stored.
It's also the reason why your Promise.reject inside that callback is ignored, and why Promise.accept never caused any problems.
You will need to create a new promise for the result of the save invocation here (so that you actually can return it):
…
var user = new User(newUser);
return new Promise(function(resolve, reject) {
user.save(function(err) {
if (err) {
console.log(err);
console.log('There is a problem saving the user info');
reject('There is a problem saving the user info');
} else {
console.log('A new user added: ');
console.log(newUser);
resolve(newUser);
}
});
}); // .then(getUserList);

Categories

Resources