From 5f53664ad7d7589b36dca94f7097404f2785ebf3 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Wed, 25 Apr 2018 22:48:01 +0200 Subject: [PATCH] return a promise when there is no callback in concat --- README.md | 15 +++++++++++++++ index.js | 7 +++++++ test/concat.js | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/README.md b/README.md index 0236dd14..87a10653 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,21 @@ get.concat('http://example.com', function (err, res, data) { }) ``` +or with async/await + +```js +const get = require('simple-get') + +async function run () { + const { res, data } = await get.concat('http://example.com') + console.log(res.statusCode) // 200 + console.log(data) // Buffer('this is the server response') + }) +} + +run().then(({ data } => console.log(data.toString())) +``` + ### POST, PUT, PATCH, HEAD, DELETE support For `POST`, call `get.post` or use option `{ method: 'POST' }`. diff --git a/index.js b/index.js index 947bb7d0..16b8b2c6 100644 --- a/index.js +++ b/index.js @@ -74,6 +74,13 @@ function simpleGet (opts, cb) { } simpleGet.concat = (opts, cb) => { + if (cb) return _concat(opts, cb) + return new Promise((resolve, reject) => { + _concat(opts, (err, res, data) => err ? reject(err) : resolve({ res, data })) + }) +} + +function _concat (opts, cb) { return simpleGet(opts, (err, res) => { if (err) return cb(err) concat(res, (err, data) => { diff --git a/test/concat.js b/test/concat.js index 4a970650..9c09be80 100644 --- a/test/concat.js +++ b/test/concat.js @@ -89,3 +89,24 @@ test('get.concat json error', function (t) { }) }) }) + +test('get.concat with Promise', function (t) { + t.plan(3) + var server = http.createServer(function (req, res) { + res.statusCode = 200 + res.end('blah blah blah') + }) + + server.listen(0, function () { + var port = server.address().port + get + .concat('http://localhost:' + port) + .then(({ res, data }) => { + t.equal(res.statusCode, 200) + t.ok(Buffer.isBuffer(data), '`data` is type buffer') + t.equal(data.toString(), 'blah blah blah') + server.close() + }) + .catch(t.fail) + }) +})