- Notifications
You must be signed in to change notification settings - Fork0
Run a list of functions in order in a given object context. The functions can be callback-taking or promise-returning.
License
isaacs/function-loop
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Run a list of synchronous or asynchronous functions, and call afunction at the end.
import{loop}from'function-loop'// or `const { loop } = require('function-loop')constloop=require('./dist/cjs/index.js').default// synchronous usageconstlist=[()=>console.log(1),()=>console.log(2),()=>console.log(3),]constresult=loop(list,()=>{console.log('done')returntrue},(er)=>{console.error('threw somehow',er)})console.log('result:',result)// logs:// 1// 2// 3// done// result: true// asynchronous usageconstplist=[async()=>console.log(1),async()=>newPromise(resolve=>setTimeout(resolve,100)).then(()=>console.log(2)),async()=>console.log(3),]constpresult=loop(plist,()=>{console.log('done')returntrue},(er)=>{console.error('threw somehow',er)})console.log('result:',presult)presult.then(()=>console.log('resolved'))// logs:// 1// result: Promise { <pending> }// 3// 2// resolved
This module is"zalgo-preserving",meaning that synchronous returns will result in a sync call tothe supplied cb, and async calls will result in the done callbackbeing called asynchronously. The loop will return a Promiseindicating when it is finished, if any async functions areencountered. It does not artificially defer if functions arecalled synchronously.
loop(functionList, doneCallback, errorCallback)
Run all the functions and then call thedoneCallback
or calltheerrorCallback
if there are any errors.
Functions are called without being bound to any object asthis
.
Functions can return a Promise to do async operations, or not ifthey are done synchronously. Throws and Promise rejection arereported to theerrorCallback
provided.
Return value is the return value of the callback, or aPromise
resolving to the callback's return value if any of the functionsin the list return promises.
About
Run a list of functions in order in a given object context. The functions can be callback-taking or promise-returning.