项目作者: SpudNyk

项目描述 :
Various functions for asynchronous operations
高级语言: TypeScript
项目地址: git://github.com/SpudNyk/async-wrappers.git
创建时间: 2019-06-06T18:02:16Z
项目社区:https://github.com/SpudNyk/async-wrappers

开源协议:MIT License

下载


async-wrappers

Implementations of debounce, throttle, retry and more targeted to promises/async/await.

Key Features

  1. call argument aggregation - all arguments from calls to the wrapper can be combined for the call to the wrapped function, using a supplied argument reducer function. See the api documentation for supplied reducers.
  2. call return values - calls to the wrapper will return a promise to wrapped function’s result.
  3. delay times of 0 are still asynchronous and will resolve on the next runtime loop.

Documentation

See the API.

Example

  1. const { debounce, combineArguments } = require('async-wrappers');
  2. const data = {
  3. 1: 'data 1',
  4. 2: 'data 2'
  5. //...
  6. };
  7. // this could be fetching from a database or webservice
  8. // debounce supports async functions or returned promises
  9. const getByIds = ids => {
  10. console.log(`Getting: ${JSON.stringify(ids)}`);
  11. const keyed = {};
  12. // this could be a server request
  13. for (const id of ids) {
  14. keyed[id] = data[id];
  15. }
  16. return keyed;
  17. };
  18. // data loader equivalent
  19. const load = debounce(getByIds, 0, {
  20. reducer: combineArguments
  21. });
  22. const loadData = async id => {
  23. const data = await load(id);
  24. return data[id];
  25. };
  26. const main = async () => {
  27. const foo = loadData(2);
  28. const bar = loadData(1);
  29. const baz = loadData(3);
  30. console.log(`Foo: ${await foo}`);
  31. console.log(`Bar: ${await bar}`);
  32. console.log(`Baz: ${await baz}`);
  33. };
  34. main();
  35. // Outputs:
  36. // Getting: [2,1,3]
  37. // Foo: data 2
  38. // Bar: data 1
  39. // Baz: undefined