bellard / quickjs

Public repository of the QuickJS Javascript Engine.
https://bellard.org/quickjs
Other
8.47k stars 888 forks source link

Running code on Promise completion or rejection #147

Closed anuragvohraec closed 1 year ago

anuragvohraec commented 1 year ago

Hi All,

I was implementing WritableStream specification (Web api).As per it I need to create a promise and and then run certain code once its fullfilled.

I am able to create promise using the JS_NewPromiseCapability, but how do I set functions to run on its fullfillment or rejection,. basicaly pass functions to its then and catch part ? All this has to be done at C side.

saghul commented 1 year ago

The resolving_funcs parameter takes an array of functions: [then, catch].

anuragvohraec commented 1 year ago

The resolving_funcs parameter takes an array of functions: [then, catch].

Thank you. And sorry if I am asking too basic questions. I have even gone through the source code to understand this, but from source code it seemed that it only supported two functions(which I guessed are resolve and reject):

static JSValue js_new_promise_capability(JSContext *ctx, JSValue *resolving_funcs, JSValueConst ctor){
//some code
//line 46699
for(i = 0; i < 2; i++)
        resolving_funcs[i] = JS_DupValue(ctx, s->data[i]);
//some code
}

And hence the confusion. Now if these were then and catch , then how do one resolve or reject a promise ?

anuragvohraec commented 1 year ago

ok so exploring github + stackoverflow, here is the overall conclusion for future referce for any one.

  1. Use JS_NewPromiseCapability to create a promise.
  2. The param resolving_funcs are the resolve and reject function.
  3. To pass then and catch callbacks, treat them as properties on promise object. And do JS_Call to pass callbacks to them.
lguipeng commented 4 months ago

ok so exploring github + stackoverflow, here is the overall conclusion for future referce for any one.

  1. Use JS_NewPromiseCapability to create a promise.
  2. The param resolving_funcs are the resolve and reject function.
  3. To pass then and catch callbacks, treat them as properties on promise object. And do JS_Call to pass callbacks to them.

Hi @anuragvohraec I have followed the three steps you mentioned to use it, but Promise's then still won't be able to call it,I also noticed the method mentioned in this(https://github.com/bellard/quickjs/issues/140), but I don't know how to solve it