Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created September 8, 2017 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/62e1b81a9300bf616d91eac04647f377 to your computer and use it in GitHub Desktop.
Save mrcoles/62e1b81a9300bf616d91eac04647f377 to your computer and use it in GitHub Desktop.
Node Unirest Promise Wrapper
function unirest_prom(unirest_req, always_resolve) {
// Returns a Promise by wrapping a unirest.Request object in
// a Promise that immediately calls `.end(...)`
//
// Params:
//
// * unirest_req - unirest.Request - any unirest Request object that has
// not yet had `.end(...)` called on it
// * always_resolve - bool (optional) - defaults to `false`, iff `true` then
// the Promise always resolves--even when the request fails
// (since HTTP errors are encapsulated in the `response`
// object). A unirest.Response object is passed to either
// `resolve` or `reject`.
//
return new Promise((resolve, reject) => {
unirest_req.end(r => {
return ((always_resolve === true ||
(r.status >= 200 && r.status < 300)) ?
resolve(r) :
reject(r));
});
});
}
@mrcoles
Copy link
Author

mrcoles commented Sep 8, 2017

As of September 2017 the unirest Node package doesn’t support promises. Here’s a simple way to wrap a unirest.Request object and turn it into a Promise instead of calling .end(…). I went ahead and had non-200 responses get rejected, unless you set always_resolve === true.

@scheung38
Copy link

scheung38 commented Feb 10, 2019

Hi @mrcoles, where is always_resolved coming from thanks

is this still working? as I tried to call it and then subsequently
const data = function unirest_prom()
console.log(await data)

i.e data is not available outside the context of the function? so if something happens like making a server call and getting back 200 statusCode, does that still make this visible outside of the call?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment