Skip to content

Instantly share code, notes, and snippets.

@bkardell
Created January 28, 2016 19:24
Show Gist options
  • Select an option

  • Save bkardell/d5c4fc89272ab1d2702f to your computer and use it in GitHub Desktop.

Select an option

Save bkardell/d5c4fc89272ab1d2702f to your computer and use it in GitHub Desktop.

Imagine that we define a function that can do a unit of work some time later called doSomeAsyncWork. You pass it how long you want to wait before doing the work and a 'work' function which receives both resolve and reject...

var doSomeAsyncWork = function (timeMs, work) {
   return new Promise(function (resolve, reject) {
       setTimeout(function () {
        work(resolve, reject);
       }, timeMs);
   });
};

Now we ask it to do some async work, but in the process we make a mistake and throw...

doSomeAsyncWork(1000, function (resolve, reject) {
   throw Error("Oh noes!");
}).catch(function (e) {
   console.log('caught async work rejection');
});

Will the console log 'caught async work rejection'? Why/why not?

@jakearchibald

Copy link
Copy Markdown

The above fails for the same reason:

try {
  setTimeout(() => throw Error("BOOM"), 5000);
}
catch(e) {
  console.log("It failed")
}

…doesn't work. The function passed to setTimeout throws, but the try/catch is no longer in the stack, as it's executed as part of a separate task.

A better way (IMO) to implement what you're trying to do is:

function wait(ms) {
  return new Promise(r => setTimeout(r, ms));
}

Then:

wait(1000).then(() => {
  console.log("Delayed!");
});

And this works as expected:

wait(1000).then(() => {
  throw Error('Boo!');
}).catch(e => {
  console.log('aww', e);
});

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