45

only-last-promise - Resolve or reject only last Promise

 4 years ago
source link: https://github.com/niksy/only-last-promise
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

only-last-promise

Resolve or reject only last Promise.

Useful if you want to "abort" already running async operations started with debounced input event.

Install

npm install only-last-promise --save

Usage

When calling the wrapper function multiple times, only the last returned Promise will resolve or reject and all other Promise s will be aborted with DiscardSignal error.

In the following example, fetch requests for /buddy and /allie will be discarded (they will return undefined ), and only /becky will be resolved with Response .

import onlyLastPromise, { DiscardSignal } from 'only-last-promise';

const wrapper = onlyLastPromise();

const wrappedFetch = async (url) => {
	try {
		return await wrapper(fetch(url));
	} catch (error) {
		if (!(error instanceof DiscardSignal)) {
			throw error;
		}
	}
};

(async () => {
	await Promise.all([
		wrappedFetch('/buddy'),
		wrappedFetch('/allie'),
		wrappedFetch('/becky')
	]);
	// => [undefined, undefined, Response]
})();

API

onlyLastPromise()

Returns: Function

Factory function which returns wrapper function.

wrapper(promise)

Type: Function

promise

Type: Promise

Promise to handle.

Browser support

Tested in IE9+ and all modern browsers, assuming Promise is available.

Test

For automated tests, run npm run test:automated (append :watch for watcher support).

License

MIT © Ivan Nikolić


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK