Last active
September 28, 2018 01:39
-
-
Save IUnknown68/97dd72386367ed5dfa8e7bc3b7a9f85f to your computer and use it in GitHub Desktop.
Promise that can be resolved with multiple values.
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
class MPromise extends Promise { | |
constructor(executor) { | |
super((resolve, reject) => | |
executor((...args) => resolve(args), (...args) => reject(args)) | |
); | |
} | |
then(onFulfilled, onRejected) { | |
return super.then( | |
onFulfilled ? (args) => onFulfilled(...args) : undefined, | |
onRejected ? (args) => onRejected(...args) : undefined | |
); | |
} | |
catch(onRejected) { | |
return super.catch((args) => onRejected(...args)); | |
} | |
} | |
// Sample: | |
function getHelloWorld() { | |
return new MPromise((resolve, reject) => { | |
resolve('Hello', 'World'); | |
// or reject with multiple arguments | |
// reject(new Error('Not Found'), 'Hello', 'World'); | |
}); | |
} | |
getHelloWorld().then((h, w) => { | |
console.log(`H is: ${h}, W is: ${w}`); | |
}).catch((error, h, w) => { | |
console.log(`Error: ${error}: ${h}, ${w}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment