Created
July 23, 2021 20:11
-
-
Save gilberto-009199/10e292cb82657d26ad84bd7c33fcc275 to your computer and use it in GitHub Desktop.
Promise polyfill es5 ie8+
This file contains 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 characters
/** Pseudo classe Promise es5 compativel ie8+ */ | |
function MyPromisePolyfill(func){ | |
var ctx = this; | |
this.resolve = function(data){ | |
ctx.then(data); | |
}; | |
this.then = function(funcResolve){ | |
ctx.then = funcResolve; | |
}; | |
this.reject = function(data){ | |
ctx.catch(data); | |
}; | |
this.catch = function(funcCatch){ | |
ctx.catch = funcCatch; | |
}; | |
this.error = function(funcCatch){ | |
ctx.error = funcCatch; | |
}; | |
setTimeout(function(){ | |
func(ctx.resolve, ctx.reject); | |
},6); | |
return ctx; | |
}; | |
// Teste assincrono | |
function promise_teste_assincronaTempo(tempo){ | |
return new MyPromisePolyfill(function(resolve, reject){ | |
// Fazendo alguma coisa asincrona!!! | |
setTimeout(function(){ | |
resolve(true); | |
},tempo) | |
}) | |
} | |
/** Verifica se já possui promise nativa */ | |
function promise_polyfill_init(){ | |
var local = {}; | |
if (typeof global !== 'undefined') { | |
local = global; | |
} else if (typeof self !== 'undefined') { | |
local = self; | |
} else if(typeof window !== 'undefined'){ | |
local = window; | |
} else { | |
try { local = Function('return this')(); } | |
catch (e) { | |
throw new Error('polyfill não pdoe carregar por não identificar o global'); | |
} | |
} | |
// Verifica se já existe a implementação da Promise nativamente | |
if (local.Promise) { | |
var promiseToString = null; | |
try { | |
promiseToString = Object.prototype.toString.call(new local.Promise(function(resolve,reject){})); | |
} catch (e) { | |
// silently ignored | |
} | |
// Para a função se o objeto Promise for dectado | |
if (promiseToString === '[object Promise]') { | |
return; | |
} | |
} | |
console.info("Não possui Promise Native!!") | |
local.Promise = MyPromisePolyfill; | |
/* Teste */ | |
promise_teste_assincronaTempo(800).then(function(data){ | |
console.log("MyPromisePolyfill UP!!") | |
}) | |
}; | |
promise_polyfill_init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment