Chain asynchronous functions (鏈?zhǔn)疆惒胶瘮?shù))
循環(huán)遍歷包含異步事件的函數(shù)數(shù)組,當(dāng)每個異步事件完成時調(diào)用 next。
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
/*
chainAsync([
next => { console.log('0 seconds'); setTimeout(next, 1000); },
next => { console.log('1 second'); setTimeout(next, 1000); },
next => { console.log('2 seconds'); }
])
*/
Curry (函數(shù)柯里化)
使用遞歸。
如果提供的參數(shù)(args)的數(shù)量足夠,則調(diào)用傳遞的函數(shù) fn,否則返回一個柯里化函數(shù)fn,等待傳入剩下的參數(shù)。
如果你想要一個接受參數(shù)數(shù)量可變的函數(shù)(一個可變參數(shù)函數(shù),例如Math.min()),你可以選擇將參數(shù)個數(shù)傳遞給第二個參數(shù)arity。
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length
? fn(...args)
: curry.bind(null, fn, arity, ...args);
// curry(Math.pow)(2)(10) -> 1024
// curry(Math.min, 3)(10)(50)(2) -> 2
Pipe (管道)
使用 Array.reduce()讓值在函數(shù)間流通。
const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
Promisify (promise轉(zhuǎn)化)
使用 currying 返回一個函數(shù),返回一個調(diào)用原始函數(shù)的 Promise。 使用 ...rest 運算符傳入所有參數(shù)。
In Node 8+, you can useutil.promisify
Node 8 版本以上,你可以使用 util.promisify
const promisify = func =>
(...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) =>
err ? reject(err) : resolve(result))
);
// const delay = promisify((d, cb) => setTimeout(cb, d))
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
Run promises in series (隊列運行promise)
使用 Array.reduce() 通過創(chuàng)建一個promise 鏈來運行一系列 promise,每個 promise在解析時返回下一個 promise。
const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
// const delay = (d) => new Promise(r => setTimeout(r, d))
// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
Sleep (睡眠)
通過返回一個 Promise延遲執(zhí)行 async 函數(shù),把它放到睡眠狀態(tài)。.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/*
async function sleepyWork() {
console.log('I\'m going to sleep for 1 second.');
await sleep(1000);
console.log('I woke up after 1 second.');
}
*/