0

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?

CogitoErgoSum
  • 2,879
  • 5
  • 32
  • 45
  • Are you asking about `request` and whether `resp.headers.status != "200"` is correct, or are you asking about promises and whether `throw 401;` is appropriate? – Bergi Jun 09 '16 at 16:08
  • Promises and whether throw 401 would be the appropriate way to go – CogitoErgoSum Jun 09 '16 at 17:07

1 Answers1

1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks! I was throwing the 401 more for simplicity at this point but agree should be using a proper error object even in mocking. – CogitoErgoSum Jun 09 '16 at 19:00