Last active
May 8, 2019 15:05
-
-
Save mattmorgis/d3f44cd76dddbb20320ad8765f475251 to your computer and use it in GitHub Desktop.
Request Stream as Promise
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
const request = require("request"); | |
function requestPromiseStream(uri, requestOptions) { | |
return new Promise(function(resolve, reject) { | |
var req = request(uri, requestOptions); | |
req.on("error", reject); | |
req.on("response", function(res) { | |
// pause the stream so that it isn't flowing during the async promise hop | |
res.pause(); | |
if (res.statusCode !== 200) { | |
if (typeof res.body === "undefined") { | |
req.on("complete", function(res) { | |
return reject( | |
new rpErrors.StatusCodeError(res.statusCode, res.body) | |
); | |
}); | |
req.readResponseBody(res); | |
return; | |
} | |
return reject(new rpErrors.StatusCodeError(res.statusCode, res.body)); | |
} | |
resolve(res); | |
}); | |
}); | |
} | |
const main = async () => { | |
const stream = await requestPromiseStream("https://google.com"); | |
for await (const chunk of stream) { | |
console.log(chunk); | |
} | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment