Skip to content

Instantly share code, notes, and snippets.

@masnun
Created February 13, 2019 17:28
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save masnun/2a8a3646eb85f1468733a43113f2fc93 to your computer and use it in GitHub Desktop.
function wait(ms) {
const ret = {};
const signal = new Promise((resolve, reject) => {
ret.cancel = () => {
reject(new Error("Promise was cancelled"));
};
});
ret.promise = new Promise((res, rej) => {
const timeOut = setTimeout(() => {
console.log("I was called");
res("ok");
}, ms);
signal.catch(err => {
rej(err);
clearTimeout(timeOut);
});
});
return ret;
}
const { promise, cancel } = wait(1000);
promise.then(res => console.log(res)).catch(err => console.log(err));
cancel();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment