Created
September 8, 2017 17:25
-
-
Save mrcoles/62e1b81a9300bf616d91eac04647f377 to your computer and use it in GitHub Desktop.
Node Unirest Promise Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
}); | |
} |
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
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 setalways_resolve === true
.