Created
August 16, 2017 06:55
-
-
Save IAIAE/3d0cd406a9a00f8a9c3aa4a558612be6 to your computer and use it in GitHub Desktop.
Revisions
-
IAIAE created this gist
Aug 16, 2017 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,43 @@ /** * 轮询,直到成功 * @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(); }) }