Created
May 7, 2020 15:13
-
-
Save Natumsol/5ad51fa59ee28150a9b2ddd5d8689e08 to your computer and use it in GitHub Desktop.
timeoutPromise
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
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