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?