Skip to content

Commit

Permalink
Add request and response events to the Promise API (#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
szmarczak authored and sindresorhus committed Jul 9, 2018
1 parent bc41a49 commit e86aad7
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@ If this is disabled, requests that encounter an error status code will be resolv

#### Streams

**Note**: Progress events, redirect events and request/response events can also be used with promises.

#### got.stream(url, [options])

Sets `options.stream` to `true`.
Expand Down Expand Up @@ -285,8 +287,6 @@ Progress events for uploading (sending request) and downloading (receiving respo

If it's not possible to retrieve the body size (can happen when streaming), `total` will be `null`.

**Note**: Progress events can also be used with promises.

```js
(async () => {
const response = await got('sindresorhus.com')
Expand Down
4 changes: 4 additions & 0 deletions source/as-promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ module.exports = options => {
req.abort();
}

proxy.emit('request', req);

onCancel(() => {
req.abort();
});
Expand All @@ -36,6 +38,8 @@ module.exports = options => {
});

emitter.on('response', async response => {
proxy.emit('response', response);

const stream = is.null(options.encoding) ? getStream.buffer(response) : getStream(response, options);

let data;
Expand Down
30 changes: 30 additions & 0 deletions test/promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import test from 'ava';
import {createServer} from './helpers/server';
import got from '..';

let s;

test.before('setup', async () => {
s = await createServer();
s.on('/', (req, res) => {
res.statusCode = 200;
res.end();
});
await s.listen(s.port);
});

test('should emit request event as promise', async t => {
await got(s.url, {json: true}).on('request', () => {
t.pass();
});
});

test('should emit response event as promise', async t => {
await got(s.url, {json: true}).on('response', () => {
t.pass();
});
});

test.after('cleanup', async () => {
await s.close();
});

0 comments on commit e86aad7

Please # to comment.