Reputation: 2907
Beginning my first significant NodeJS app and I am unsure if I am leveraging promises properly. In my case I am sending an AJAX request and then once it's done want to return something (In this case send back a specific status code and message to the browser). I'm doing additional validation in the then block but I'm not sure if I'm executing this right. Any insight would be appreciated.
var Promise = require("bluebird");
var request = Promise.promisify(require("request"));
Promise.promisifyAll(request);
...
request({
url: 'https://my.url.com', //URL to hit
method: 'POST',
headers: {
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
},
body: jsonStringVar //Set the body as a string
}).then(function (resp) {
if(resp.headers.status != "200") {
throw (401)
}
console.log(resp);
console.log(resp.headers.status);
res.status(201);
res.json({
"status": "Success"
});
}).catch(function (err) {
console.log(err)
res.status(500);
res.json({
"status": "bam"
});
});
I feel like I'm incorrectly checking the resp.header.status in the chained function and throwing an error. Is there a better way to do custom validation and throw an error or would this be the accepted practice to error out a promise?
Upvotes: 0
Views: 51
Reputation: 664195
Is throwing an error the accepted practice to error out a promise?
Yes, it is. Promises were designed to do that, it's quite equivalent to throwing exceptions in a synchronous function and catching them with a try
statement. Of course you can also use if
else for conditional validation tasks, but throwing is fine.
What you should not do is to throw the number 401
, better always throw Error
objects.
Upvotes: 1