Skip to content

Latest commit

 

History

History
101 lines (65 loc) · 2.77 KB

File metadata and controls

101 lines (65 loc) · 2.77 KB

> Back to homepage

Promise API

Source code: source/as-promise/index.ts

The main Got function returns a Promise.
Although in order to support cancelation, PCancelable is used instead of pure Promise.

got(url: string | URL, options?: OptionsInit, defaults?: Options)

Returns: Promise<Response>

The most common way is to pass the URL as the first argument, then the options as the second.

import got from 'got';

const {headers} = await got(
	'https://httpbin.org/anything',
	{
		headers: {
			foo: 'bar'
		}
	}
).json();

got(options: OptionsInit)

Returns: Promise<Response>

Alternatively, you can pass only options containing a url property.

import got from 'got';

const {headers} = await got(
	{
		url: 'https://httpbin.org/anything',
		headers: {
			foo: 'bar'
		}
	}
).json();

This is semantically the same as the first approach.

promise.json<T>()

Returns: Promise<T>

A shortcut method that gives a Promise returning a JSON object.

It is semantically the same as settings options.resolveBodyOnly to true and options.responseType to 'json'.

promise.buffer()

Returns: Promise<Buffer>

A shortcut method that gives a Promise returning a Buffer.

It is semantically the same as settings options.resolveBodyOnly to true and options.responseType to 'buffer'.

promise.text()

Returns: Promise<string>

A shortcut method that gives a Promise returning a string.

It is semantically the same as settings options.resolveBodyOnly to true and options.responseType to 'text'.

promise.on(event, handler)

The events are the same as in Stream API.

promise.off(event, handler)

Removes listener registered with promise.on

import {createReadStream} from 'node:fs';
import got from 'got';

const ongoingRequestPromise = got.post(uploadUrl, {
    body: createReadStream('sample.txt')
});

const eventListener = (progress: Progress) => {
    console.log(progress);
};

ongoingRequestPromise.on('uploadProgress', eventListener);

setTimeout(() => {
    ongoingRequestPromise.off('uploadProgress', eventListener);
}, 500);

await ongoingRequestPromise;