Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promises #388

Open
baxtersa opened this issue Jul 20, 2018 · 3 comments
Open

Promises #388

baxtersa opened this issue Jul 20, 2018 · 3 comments

Comments

@baxtersa
Copy link
Contributor

baxtersa commented Jul 20, 2018

I'm working on this in the context of distributed continuations, which is much harder, but here's a polyfill for Promise.prototype.then that works with native Promises (probably modulo some error handling).

const rts = <stopify-runtime>;
const originalThen = Promise.prototype.then;
Promise.prototype.then = function <T1, T2>(onFulfilled: (v: any) => T1 | PromiseLike<T1>,
  onRejected: (e: any) => T2 | PromiseLike<T2>): Promise<T1 | T2> {

  function wrapFulfilled(v: any) {
    return rts.runtime(() =>, (doneV) => onFulfilled(doneV.value));
  }

  function wrapRejected(e: any) {
    if (e instanceof Capture) {
      return rts.runtime(() => { throw e; },
        v => {
          if (v.type === 'normal') {
            return wrapFulfilled(v.value);
          } else {
            return onRejected(v.value);
          }
        });
    } else if (reject) {
      return onRejected(e);
    } else {
      throw e;
    }
  }

  return originalThen.call(this, wrapFulfilled, wrapRejected);
}

As I work out the rest of promises I'll try to introduce this into stopify.

@jvilk
Copy link

jvilk commented Jul 20, 2018

Maybe I'm missing something, but native Promise.prototype.then doesn't pass resolve and reject parameters to the callback. You only get those with the Promise constructor.

@baxtersa
Copy link
Contributor Author

My variable names might be misleading here, I'll edit them. But Promise.prototype.then has the signature

(onFulfilled: (value: any) => T1 | PromiseLike<T1>, onRejected: (reason: any) => T2 | PromiseLike<T2>) => Promise<T1 | T2>

So native Promise.prototype.then gets called with two callbacks (second one optional).

@baxtersa
Copy link
Contributor Author

To clarify, these are the user-provided callbacks, not the internal Promise resolve/reject functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants