Skip to content

Instantly share code, notes, and snippets.

@webkong
Last active January 11, 2021 12:12
Show Gist options
  • Save webkong/ad35a21cbdfef30ed9d287e6bad2e4fd to your computer and use it in GitHub Desktop.
Save webkong/ad35a21cbdfef30ed9d287e6bad2e4fd to your computer and use it in GitHub Desktop.
JavaScript工具函数
const asyncSequentializer = (() => {
const toPromise = (x) => {
if(x instanceof Promise) { // if promise just return it
return x;
}
if(typeof x === 'function') {
// if function is not async this will turn its result into a promise
// if it is async this will await for the result
return (async () => await x())();
}
return Promise.resolve(x)
}
return (list) => {
const results = [];
return list
.reduce((lastPromise, currentPromise) => {
return lastPromise.then(res => {
results.push(res); // collect the results
return toPromise(currentPromise);
});
}, toPromise(list.shift()))
// collect the final result and return the array of results as resolved promise
.then(res => Promise.resolve([...results, res]));
}
})();
// 轮询数据
// 如果你需要持续检查数据更新,但系统中没有 WebSocket,则可以使用这个工具来执行操作。它非常适合上传文件时,想要持续检查文件是否已完成处理的情况,或者使用第三方 API(例如 dropbox 或 uber)并且想要持续检查过程是否完成或骑手是否到达目的地的情况。
async function poll(fn, validate, interval = 2500) {
const resolver = async (resolve, reject) => {
try { // catch any error thrown by the "fn" function
const result = await fn(); // fn does not need to be asynchronous or return promise
// call validator to see if the data is at the state to stop the polling
const valid = validate(result);
if (valid === true) {
resolve(result);
} else if (valid === false) {
setTimeout(resolver, interval, resolve, reject);
} // if validator returns anything other than "true" or "false" it stops polling
} catch (e) {
reject(e);
}
};
return new Promise(resolver);
}
const stringify = (() => {
const replacer = (key, val) => {
if(typeof val === 'symbol') {
return val.toString();
}
if(val instanceof Set) {
return Array.from(val);
}
if(val instanceof Map) {
return Array.from(val.entries());
}
if(typeof val === 'function') {
return val.toString();
}
return val;
}
return (obj, spaces = 0) => JSON.stringify(obj, replacer, spaces)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment