Skip to content

Instantly share code, notes, and snippets.

@delapuente
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delapuente/9055624 to your computer and use it in GitHub Desktop.
Save delapuente/9055624 to your computer and use it in GitHub Desktop.
Mock promise supported interface to produce delayed values
function fPromise(timeout, result, error) {
return new Promise(function(fulfill, reject) {
setTimeout(function () {
if (!error) fulfill(result);
else if (error instanceof Error) throw error;
else reject(error);
}, timeout);
});
}
/*
How to use:
- Fulfilled promise: fPromise(1000, 'ok-result');
- Rejected promise: fPromise(1000, null, 'error-result');
- Throwing promise: fPromise(1000, null, new Error('message'));
*/
@jmendiara
Copy link

doing a throw in other event loop cycle, will never get caught by promises. (Unless you are using zone.js or nodejs domains)

This should work

function doSomething() {
  return new Promise(...);
}


doSomething
  .then(function() {
    throw new Error('will be caught');
  })
  .catch(function(err) {
     console.log(err.message);
  });

@delapuente
Copy link
Author

Yep. Notice the gist try to simulate an async implementation throwing an Error, not a handler throwing an error. Nothing more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment