同时支持回调和Promise的函数-callbackOrPromiseFn

有时我们希望函数可以同时支持回调和Promise

var callbackOrPromiseFn = function (fn) {
    return function (success, fail) {
        return new Promise((resolve, reject) => {
            var successFn = (res) => {
                if (success) success(res)
                if (resolve) resolve(res)
            }
            var failFn = (res) => {
                if (fail) fail(res)
                if (reject) reject(res)
            }
            fn(successFn, failFn)
        })
    }
}

test:

var fn=callbackOrPromiseFn(function(n,success,fail){
	n>1?success():fail()
})(success,fail)
var success=function(){console.log('success')}
var fail=function(){console.log('fail')}
fn(2,success,fail)
fn(0).then(success).catch(fail)

  

posted @ 2020-07-28 18:05  朱现国  阅读(317)  评论(0编辑  收藏  举报