Last active
June 21, 2018 06:50
-
-
Save samundrak/92a915e0ecfc9928c19da159f6139221 to your computer and use it in GitHub Desktop.
Synchronous promise resolver
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 characters
const pr = (shouldResolve = true, time = 5000) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(`this promise is ${shouldResolve}`); | |
if (shouldResolve) { | |
resolve(); | |
} else { | |
reject(new Error('failed')); | |
} | |
}, time); | |
}); | |
}; | |
const prs = [() => pr(true), () => pr(false, 10000), () => pr(true)]; | |
function synchronousPromiseResolver(promises) { | |
const copyOfPromises = [...promises]; | |
const promisesAnswer = []; | |
return new Promise((resolve, reject) => { | |
const prResolver = function(promise) { | |
if (!promises.length || !promise) { | |
return resolve(promisesAnswer); | |
} | |
promise() | |
.then(data => { | |
promisesAnswer.push(data); | |
prResolver(copyOfPromises.shift()); | |
}) | |
.catch(err => { | |
reject(err); | |
}); | |
}; | |
prResolver(copyOfPromises.shift()); | |
}); | |
} | |
synchronousPromiseResolver(prs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment