0.1.1 • Published 2 years ago

async-bus v0.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

AsyncBus

1.安装

npm install async-bus

or

yarn add async-bus

2.特性

在使用传统的 eventBus 时,发出时间之后,不知道订阅者何时结束动作。 async-bus 通过 emit 后返回 Promise 可以监听订阅返回。

3.使用

3.1 使用默认导出

// 监听函数定义
interface AsyncBusFn {
  (args?: object | string | number, resolve?: Function, reject?: Function): Promise<any> | void;
}
import asyncBus from 'async-bus'

const handleTest = (args: any) => {
    console.log(args);
};

const handleTest1 = (args: any, resolve: any, reject: any) => {
  setTimeout(() => {
    resolve(args);
  }, 2000);
};

const handleTest2 = (args: any) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("test2");
    }, 2000);
  });
};


const handleTest3 = () => {
  return fetch("https://www.baidu.com/").then((res) => {
    console.log(args)
    return res;
  });
};

asyncBus.on("test", handleTest);
asyncBus.on("test", handleTest1);
asyncBus.on("test", handleTest2);
asyncBus.on("test", handleTest3);

asyncBus
  .emit("test", {
    msg: "abc",
  })
  .then((res) => {
    // 等待四个订阅者执行完毕之后执行
    // 返回 Promise.all
    console.log(res);
  })
  .catch((err) => {
    // 执行出错 订阅者reject或者超时
    console.log(err);
  });

3.2 使用类

set timout in your async-bus

import { AsyncBus } from 'async-bus'

const ab = new AsyncBus(5000) 

export default ab
acornacorn-jsxajvacorn-globalsababacorn-walkansi-colorsargparseansi-escapesansi-regexarray-equalansi-stylesaria-queryanymatcharray-unionarr-diffarr-flattenarr-unionarray-includesarray-uniqueassert-plusastral-regexarray.prototype.flatarray.prototype.flatmapasn1at-least-nodeast-types-flowaws-sign2atobasynckitassign-symbolsaws4babel-jestaxobject-queryaxe-coreasyncrobabel-plugin-annotate-pure-callsbabel-plugin-dev-expressionbabel-plugin-istanbulbabel-eslintbabel-plugin-jest-hoistbabel-plugin-dynamic-import-nodebabel-plugin-polyfill-corejs3babel-plugin-transform-rename-importbabel-plugin-polyfill-corejs2balanced-matchbabel-plugin-macrosbabel-preset-jestbrace-expansionbcrypt-pbkdfbrowser-process-hrtimebasebabel-plugin-polyfill-regeneratorbinary-extensionsbabel-preset-current-node-syntaxbserbuffer-frombracesbrowser-resolvecallsitesbs-loggercache-basebrowserslistbytes-iecbuiltin-modulescaniuse-litecapture-exitcall-bindchalkcaselessci-job-numbercamelcaseclass-utilschardetchokidarci-infocli-spinnerscli-cursorcliuicli-widthcocolor-nameclonecommondircollection-visitconcat-mapcomponent-emittercombined-streamconfusing-browser-globalscommandercollect-v8-coveragecolor-convertcore-js-compatcssomcopy-descriptorcore-util-iscosmiconfigdebugcore-js-pureconvert-source-mapcssstyledashdashdefaultscross-spawndata-urlsdamerau-levenshteindecamelizedeep-isdelayed-streamdecode-uri-componentdefine-propertydir-globdetect-newlinedomexceptiondeepmergeecc-jsbndefine-propertiesdiff-sequenceselectron-to-chromiumdoctrineend-of-streamerror-exemoji-regexesbuildes-abstractenquireresbuild-windows-64eslintescape-string-regexpescaladees-to-primitiveeslint-config-prettierescodegeneslint-config-react-appeslint-import-resolver-nodeeslint-module-utilseslint-scopeeslint-plugin-jsx-a11yeslint-visitor-keyseslint-plugin-importeslint-utilsesrecurseesqueryeslint-plugin-reactespreeestraverseeslint-plugin-flowtypeesutilseslint-plugin-prettiereslint-plugin-react-hooksexec-shexecafast-deep-equalexpectesprimaestree-walkerexitextendfast-json-stable-stringifyexpand-bracketsexternal-editorfile-entry-cachefast-difffast-globextsprintfextend-shallowfb-watchmanfast-levenshteinextglobfastqfind-upfill-rangefind-cache-dirfiguresforever-agentflattedfor-inflat-cachefs.realpathform-datagensyncfs-extraget-caller-filefunctional-red-black-treefragment-cacheget-intrinsicget-stdinget-package-typegetpassget-valuefunction-bindglob-parentglobalsglobrexgrowlyget-symbol-descriptionget-streamglobalyzerglobbyglobgraceful-fshas-flaghas-valuehas-symbolshashar-schemahar-validatorhtml-encoding-snifferhas-bigintshosted-git-infohas-valuesimport-freshhas-tostringtagimurmurhashignorehttp-signaturehuman-signalsinflightinheritshtml-escapericonv-litehumanize-durationimport-localis-arrayishinquirerinternal-slotinterpretis-bigintis-ciis-boolean-objectip-regexis-accessor-descriptoris-binary-pathis-callableis-data-descriptoris-dockeris-bufferis-date-objectis-extglobis-core-moduleis-globis-generator-fnis-descriptoris-interactiveis-moduleis-extendableis-fullwidth-code-pointis-negative-zerois-numberis-plain-objectis-number-objectis-shared-array-bufferis-referenceis-regexis-streamis-typedarrayis-symbolis-stringistanbul-lib-reportis-wslisexeis-windowsistanbul-lib-coveragejest-diffisarrayjestisobjectisstreamistanbul-lib-source-mapsjest-cliistanbul-reportsjest-configjest-docblockjest-changed-filesjest-get-typeistanbul-lib-instrumentjest-environment-nodejest-eachjest-leak-detectorjest-haste-mapis-weakrefjest-mockjest-message-utiljest-jasmine2jest-regex-utiljest-matcher-utilsjest-resolve-dependenciesjest-runnerjest-resolvejest-serializerjest-environment-jsdomjest-runtimejest-utiljest-watch-typeaheadjest-workerjest-validatejs-tokensjpjsjest-watcherjson-schema-traversejsdomjson-stable-stringify-without-jsonifyjest-snapshotjest-pnp-resolverjsbnjson-parse-even-better-errorsjson-schemajsescjsprimlevnjsonfilejson5js-yamljson-stringify-safelanguage-subtag-registrykind-ofkleurjsx-ast-utilslilconfiglevenlines-and-columnslocate-pathlodashlanguage-tagslodash.mergelodash.debouncelog-updatelog-symbolslodash.memoizelolexloose-envifylower-caselru-cachelodash.sortbymakeerrormake-errormap-cachemap-visitmime-dbmake-dirmerge2merge-streamminimatchmagic-stringmimic-fnmsmicromatchmkdirpmute-streammime-typesmixin-deepnanoidminimistnanospinnermrinatural-comparenode-int64node-releasesnice-tryno-casenanomatchnpm-run-pathoauth-signnwsapinormalize-package-dataobject-assignnormalize-pathnode-notifierobject-visitobject-copyobject-inspectobject-keysobject.assignobject.entriesobject.hasownos-tmpdironceoptionatorobject.valuesobject.pickparent-moduleobject.fromentriesonetimep-each-seriesorap-finallyp-limitparse5p-locatep-trypath-parsepascal-casepath-existspath-is-absolutepath-keyparse-jsonpascalcasepicocolorspath-typeprelude-lsprettierpiratespicomatchpretty-formatpnperformance-nowpkg-dirprogresspromptsprettier-linter-helpersposix-character-classespumppunycodeprogress-estimatorqsreact-isprop-typespslread-pkg-uprandombytesregenerator-runtimereaddirpregenerateread-pkgrealpath-nativequeue-microtaskregex-notregexpprechoirregenerate-unicode-propertiesregexp.prototype.flagsregenerator-transformrepeat-elementremove-trailing-separatorrequest-promise-nativeregexpu-coreregjsparserrequest-promise-corerepeat-stringrequestrequire-directoryregjsgenresolve-fromrequire-main-filenameresolve-cwdresolve-urlretrimrafresolvereusifyrolluprestore-cursorrollup-pluginutilsrollup-plugin-terserrun-asyncrollup-plugin-sourcemapsrun-parallelsafe-regexrxjssadersvpsanesafe-bufferset-blockingsaxesserialize-javascriptsemvershellwordsshebang-regexsisteransisafer-buffershebang-commandslashset-valueshelljssignal-exitsnapdragonside-channelsnapdragon-nodeslice-ansisource-mapsource-map-resolvespdx-exceptionssnapdragon-utilsourcemap-codecsource-map-urlspdx-correctsource-map-supportspdx-expression-parsesprintf-jsstack-utilsstatic-extendspdx-license-idsstealthy-requiresplit-stringstring-lengthstrip-ansisshpksupports-colorstrip-json-commentsstrip-bomstrip-eofstring.prototype.trimendstring.prototype.matchallstring.prototype.trimstartsupports-hyperlinksstrip-final-newlinestring-widthtableterminal-linksymbol-treethroatsupports-preserve-symlinks-flagtersertest-excludetiny-globtext-tablethroughtmplto-fast-propertiestmpto-object-pathtough-cookietype-checkto-regexto-regex-rangetsutilstunnel-agenttr46type-detecttsconfig-pathstype-festtweetnaclunbox-primitiveunicode-canonical-property-names-ecmascriptunion-valueuri-jstypedarray-to-bufferunicode-match-property-ecmascriptuniversalifyunicode-property-aliases-ecmascripturixunset-valueuseunicode-match-property-value-ecmascriptw3c-hr-timeuuidv8-compile-cachewebidl-conversionswalkerwhatwg-encodingv8-to-istanbulw3c-xmlserializerverrorwhatwg-mimetypewhatwg-urlwcwidthvalidate-npm-package-licensewhich-modulewhichwrappywswrap-ansiword-wrapyallistwhich-boxed-primitiveyargs-parserwrite-file-atomicwritey18nyamlxml-name-validatorxmlcharsyargs
0.1.1

2 years ago

0.1.0

2 years ago