Skip to content

Instantly share code, notes, and snippets.

@Natumsol
Created May 7, 2020 15:13
Show Gist options
  • Save Natumsol/5ad51fa59ee28150a9b2ddd5d8689e08 to your computer and use it in GitHub Desktop.
Save Natumsol/5ad51fa59ee28150a9b2ddd5d8689e08 to your computer and use it in GitHub Desktop.
timeoutPromise
function timeoutPromise(Pro, timeout) {
return new Promise((resolve, reject) => {
const start = Date.now();
let timeId = setInterval(() => {
const now = Date.now();
if (now - start >= timeout) {
clearInterval(timeId);
reject('timeout');
}
}, 16);
return Pro.then(resolve);
})
}
// test
var sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
var getData = () => {
return sleep(10000).then(() => {
return { data:'xxx'}
});
}
timeoutPromise(getData(), 2000).then(console.log).catch(console.warn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment