Skip to content

Instantly share code, notes, and snippets.

@ccwq
Last active August 1, 2017 06:11
Show Gist options
  • Save ccwq/710e55e54d26f12e8e2e8d14a42de9d3 to your computer and use it in GitHub Desktop.
Save ccwq/710e55e54d26f12e8e2e8d14a42de9d3 to your computer and use it in GitHub Desktop.
promise相关
/**
* 转换callbak到promise形式
* ex1:有一个api getGeo(success,fail);
* 使用后
* callbackToPromise.call(getGeo,arg1,arg2,"|",arg-2,arg-1).then ...
* ex2:callbackToPromise.call({callback:api.getGeo,scope:api},arg1,arg2,"|",arg-2,arg-1).then...
* @returns {Promise}
*/
var callbackToPromise = function(){
var args = Array.prototype.slice.call(arguments);
var func = this;
return new Promise(function(resolve,reject){
var splitIndex = _.indexOf(args,"|");
if(splitIndex==-1) {
splitIndex=args.length;
}
args.splice(splitIndex,1,resolve,reject)
if(!func) {
resolve("调用的方法不存在")
}
if(typeof func == "function") {
func.apply(null,args);
}else if(func.callback){
func.callback.apply(func.scope,args)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment