Skip to content

Instantly share code, notes, and snippets.

@justan
Last active March 1, 2017 13:09
Show Gist options
  • Save justan/5e6603c64f1c1cb2fecffe267d7bc8cb to your computer and use it in GitHub Desktop.
Save justan/5e6603c64f1c1cb2fecffe267d7bc8cb to your computer and use it in GitHub Desktop.
combine duplicate promise
//通用 promise 合并
var duplicatePromiseCombine = function () {
var pendings = { }
/**
* @param {Function} promiseFn 原始的 promise 方法
* @param {Function} keyGenFn 相同的 promise 通过该方法应该返回相同的 key
* @return {Function} 可合并相同 key promise 的方法
*/
return function (promiseFn, keyGenFn) {
return function() {
var key = keyGenFn.apply(null, arguments)
if (pendings[key]) {
return pendings[key].then(function (data) {
return clone(data)
})
} else {
pendings[key] = promiseFn.apply(this, arguments)
return pendings[key].then(function(data) {
delete pendings[key]
return data
}, function(err) {
delete pendings[key]
throw err
})
}
}
}
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment