Skip to content

Instantly share code, notes, and snippets.

@IAIAE
Created August 16, 2017 06:55
Show Gist options
  • Select an option

  • Save IAIAE/3d0cd406a9a00f8a9c3aa4a558612be6 to your computer and use it in GitHub Desktop.

Select an option

Save IAIAE/3d0cd406a9a00f8a9c3aa4a558612be6 to your computer and use it in GitHub Desktop.
polling request with maxCount or maxTimeout
/**
* 轮询,直到成功
* @param {Function} promiseFunc 每次执行的回调,promiseFunc应该返回一个promise
* @param {Function} cb 用于判断promise调用是否成功
* @param {Object} config 配置: maxCount, interval, maxTimeout
*/
export default function polling(promiseFunc, cb, config) {
let count = 0;
config = config || {}
let maxCount = config.maxCount || 2;
let interval = config.interval || 0;
let maxTimeout = config.maxTimeout || 10000; //默认10秒的延时
return new Promise((done, notDone) => {
let startTime = +new Date;
let errArr = [];
function foo() {
count++;
console.info('polling try '+count+' times');
if (count > maxCount) {
return notDone({ msg: '=====polling maxCount exceed:: '+maxCount+' times', err: errArr });
}
if( (+new Date) - startTime > maxTimeout){
return notDone({msg: '======polling maxTimeout:: '+ maxTimeout+'ms', err: errArr });
}
let promise = promiseFunc();
promise.then(_=>{
let result = cb(_);
if(result === true){
done(_)
}else if(result === false){
errArr.push('customer_error')
setTimeout(foo, interval)
}else{
done(_)
}
}).catch(_ => {
errArr.push(_)
setTimeout(foo, interval)
});
}
foo();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment