Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

⁉️ AsyncAF (A.K.A. async-af, A.K.A. Async/Await Fun) - chainable asynchronous JavaScript methods that mirror their native counterparts and other tools for your asynchronous utility belt--zero dependencies

License

NotificationsYou must be signed in to change notification settings

AsyncAF/AsyncAF

Repository files navigation

npm package size (min + gzip)npm versionyarn versionunpkg versioncodecovMIT License


Working with promises or async/await?

Use AsyncAF to transform your code into beautiful asynchronous JavaScript chains, with methods similar to the ones we all know (and love! 😍) such asmap,forEach,filter,reduce, and more.

Check out the docs for all available methods. 💙

Usage

constAsyncAF=require('async-af');functiongetActiveUsers(userIds){returnAsyncAF(userIds)// map user ids to user objects with an async function.mapAF(asyncuserId=>{constuser=awaitfetch(`fake-game-api/users/${userId}`);returnuser.json();})// filter by active users.filterAF(user=>user.isActive);}

AsyncAF methods are await-able and then-able.

asyncfunctionsendMsgToActiveUsers(msg){constactiveUsers=awaitgetActiveUsers([1,2,3]);// send each active user a msg in seriesawaitAsyncAF(activeUsers).series.forEachAF(async({id})=>{awaitsendMsg(id,msg);// hypothetical msg service that's rate-limited});console.log('message sent!');}functiondoSomethingElseWithActiveUsers(){returngetActiveUsers([1,2,3]).then(activeUsers=>{// ... do something else});}

If aPromise is passed intoAsyncAF, it will be settled before a method processes it.

constuserMsg=Promise.resolve('I\'m [restricted word] AF right now')constmsgContainsBadWord=(msg,word='[restricted word]')=>AsyncAF(msg).includesAF(word);msgContainsBadWord(userMsg);// resolves to true

Array methods will settle any promises in an array before processing them.

constfindHighScoringUser=()=>AsyncAF([fetch('fake-game-api/users/1').then(user=>user.json()),// {id: 1, name: Aiden, score: 9001, ...}{id:2,name:'Bill',score:3600,/* ... */},{id:3,name:'Cari',score:5800,/* ... */},]).findAF(({score})=>score>9000);findHighScoringUser();// resolves to {id: 1, name: Aiden, score: 9001, ...}

Note: All'AF' methods have an'AF-less' alias so you can choose whether or not to make it obvious that they're AsyncAF methods.

For example:

constpromises=[1,2,3].map(n=>Promise.resolve(n));AsyncAF(promises).map(n=>n*2).filter(n=>n!==4).forEach(n=>console.log(n));// orAsyncAF(promises).mapAF(n=>n*2).filterAF(n=>n!==4).forEachAF(n=>console.log(n));// both log 2 then 6

Installation 💾

Easy peasy, just

$ npm install --save async-af,

right?

⚠️ Not so fast; there's actually several ways to include AsyncAF in your project/production site from easy to more complex:

Easy 👍
🔹npm:$ npm install --save async-af

🔸yarn:$ yarn add async-af

🔹bower:async-af is no longer published to bower. To continue using it with bower, look intobower-npm-resolver.

🔸cdn: See the table for which script tag to use:

modebrowsersscript tag
developmentmodern (ES6+)<script src="https://unpkg.com/async-af/index.js"></script>
developmentlegacy (ES5+)<script src="https://unpkg.com/async-af/legacy/index.js"></script>
productionmodern (ES6+)<script src="https://unpkg.com/async-af/min.js"></script>
productionlegacy (ES5+)<script src="https://unpkg.com/async-af/legacy/min.js"></script>


More Complex 🤔

🔹scoped packages:

Instead of pulling in the entire AsyncAF library, you can install smaller standalone packages for each of the AsyncAF methods you intend to use; for example,@async-af/map and/or@async-af/filter; see further instructions in the documentation forAsyncAfWrapper andAsyncAfWrapper.use.

🔸scoped packages +babel-plugin-transform-imports:

If you use more than a few AsyncAF scoped packages in a file, you might start to build a wall ofimport statements to pull them all in. If this is an eyesore for you, look intobabel-plugin-transform-imports and condense that ugly wall down to a singleimport statement! SeeWrapper/Use: Too Many 🤬 Imports!? for a tutorial.

🔹es modules:

AsyncAF as well as its scoped packages are also published as es modules. This gives an opportunity to conditionally loadasync-af with ES6+ features in modern browsers andasync-af with ES5-compatible features in legacy browsers.

Using the cdn scripts as an example:

<script type="module" src="https://unpkg.com/async-af/esm/index.js"></script><script nomodule src="https://unpkg.com/async-af/legacy/index.js"></script>

or minimized for production:

<script type="module" src="https://unpkg.com/async-af/esm/min.js"></script><script nomodule src="https://unpkg.com/async-af/legacy/min.js"></script>

The script with<script type="module"> will load in any browser capable of loading es modules, while the script with<script nomodule> will act as a fallback for legacy browsers.

Seehere andhere for further reading on this strategy.


A couple notes on performance 🚀

Built on Promises

Despite AsyncAF's name (Async/Await Fun), its source code is written entirely without the use ofasync/await. Its chainable asynchronous JavaScript methodsare, however, highly useful whenyour code makes use ofasync/await orPromises. This is important for performance because transpiling anasync function with babel currentlyresults in some loooong code due to pulling in things likeFacebook's regenerator and others to make it work.

Because AsyncAF instead runs your code with Promises behind the scenes, there's no need to transpileasync/await in its ES6 or ES5-compatible distributions. This boils down to much smaller bundles when compared to an equivalent async library writtenwithasync/await.

Useseries wisely

The majority of AsyncAF'sArray methods process promises in parallel by default. However, many methods have an option to process promises in series as well. You can tell AsyncAF to process promises in series within the next method invocation by setting a flag withseries or its aliasio (in order). See the documentation forseries for a full list of methods this works on.

In some cases, the time it takes to resolve an AsyncAF expression won't differ; for example:

importAsyncAF,{logAF}from'async-af';importdelayfrom'delay';logAF.options({label:false});constbools=[()=>delay(3000,{value:true}),()=>delay(2000,{value:false}),()=>delay(1000,{value:false}),];logAF('parallel',AsyncAF(bools).someAF(n=>n()));logAF('series',AsyncAF(bools).series.someAF(n=>n()));// series true// in 3.000 secs// parallel true// in 3.000 secs

Other times, processing promises in parallel will be faster:

constbools=[()=>delay(3000,{value:false}),()=>delay(2000,{value:true}),()=>delay(1000,{value:false}),];logAF('parallel',AsyncAF(bools).someAF(n=>n()));logAF('series',AsyncAF(bools).series.someAF(n=>n()));// parallel true// in 3.000 secs// series true// in 5.000 secs

And yet other times, processing promises in series will be faster:

constbools=[()=>delay(3000,{value:true}),()=>delay(4000,{value:false}),()=>delay(5000,{value:false}),];logAF('parallel',AsyncAF(bools).someAF(n=>n()));logAF('series',AsyncAF(bools).series.someAF(n=>n()));// series true// in 3.000 secs// parallel true// in 5.000 secs

Being cognizant of when to useseries vs. when to rely on the default parallel behavior can help increase the performance of your asynchronous code.

Another use case forseries might be if you're sending multiple requests to a rate-limited API. In that case you may not want to throw a ton of parallel requests at the API, but rather wait for each one in series.

Love AsyncAF?star it on GitHub

See something to improve?File an issue orsee how to contribute.💙

License

AsyncAF is licensed under theMIT License, so you can pretty much use it however you want

(butclick here orhere to get into specifics).

FOSSA Status

About

⁉️ AsyncAF (A.K.A. async-af, A.K.A. Async/Await Fun) - chainable asynchronous JavaScript methods that mirror their native counterparts and other tools for your asynchronous utility belt--zero dependencies

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp