Before async/await, when my code used callbacks, I was able to do three things: (1) call the callback with a result, (2) call the callback with an Error, or (3) not call the callback at all.
Case (3) was used in situations like this: say that you have a zoom button and a user can click it to render an image at a higher resolution, and this is an async process. If the user clicks the zoom button again, then the first render is no longer relevant, and can be canceled to let the new zoom level render run. I handled this by returning from inside the function without calling the callback, e.g.
if (process.wasCanceled()) {
return;
}
// ...
callback(someResult);
With async/await, there are only two things that you can do: return or throw. Currently, I've been using throw to indicate that the operation was canceled, since returning can falsely indicate that upstream processes should keep running. But the problem with throwing is that all the upstream callers need to know that it's not really an error, per se, and so they may need to check the type of the error.
Another crazy idea I had was to create a promise that never returns. E.g. await never()
, where the function is defined like this:
async function never () {
return new Promise(function () {});
}
That is sort of the equivalent of not calling a callback.
But I don't know if that would just leak memory over and over.
Is there a better equivalent without the drawbacks I mentioned above?