使用JavaScript中的代理实现可更新的承诺

huangapple go评论80阅读模式
英文:

Updatable promises using proxy in JavaScript

问题

PROBLEM:

似乎在某些情况下起作用,例如在控制台或JSFiddle中。但当我在服务工作者中使用它时实际上不起作用,只返回承诺的旧值。我正在使用Workbox,如果相关的话。

PRECISE QUESTION:

我想知道一些事情:

  1. 它是否真的像上面提到的那样工作?(即它的工作方式与Promise完全相同,唯一的例外是它可以被“重置”,一旦更新,所有挂起的await或附加的回调都会履行为新的更新值)
  2. 如果是,那么在(Workbox的)服务工作者中它为什么不起作用的原因是什么?
  3. 如果不是,那么实际上发生了什么?
  4. 如果它确实起作用,那么是否可能添加一个state成员变量以同步跟踪Promise的状态?(我尝试过一次,完全不起作用)

编辑2:

显然,在服务工作者中这实际上似乎也起作用。由于其他一些函数不断将Promise更新为存储在数据库中的值,因此该Promise一直被更新。

但是,我仍然希望获得对我的其他问题的答案。

英文:

EDIT: I've updated this question, and the old question is moved here.

A POC can be found on this jsfiddle
or the snippet below


GOAL:

The goal here is to make or rather simulate a promise that can be updated, whose lifecycle can be essentially reset.

Optionally, I wanted more control over promise resolution using inversion of control, like this:

const ex = {};
  const prom = new Promise<T>((resolve, reject) => {
    ex.resolve = resolve;
    ex.reject = reject;
  });

IMPLEMENTATION:

Snippet:

You can type in the new value, and choose whether to reject or resolve the promise. Rejected values will be highlighted.

>By default the promise is rejected with a value default.

Edit: By default, there's a .then() callback attached (line 85 in snippet). So once you resolve or reject with a value for the first time, you'll see your value printed twice, which is the expected behavior.

<!-- begin snippet: js hide: true console: true babel: false -->

<!-- language: lang-js -->

class UpdatablePromise {
  /**
   * @param prom - the default promise object
   * @param executor - optional ExternalExecutor argument to store executor internally.
   * @returns UpdatablePromise
   */
  constructor(prom, executor) {
    this.value = undefined;
    this.executors = [];
    if (executor) this.executors.push(Object.assign({}, executor));
    /**
     * Call previous resolve/reject functions to fulfil previous promises, if any.
     * helper function, just to reduce code duplication in `update` function.
     */
    const prevResolvers = (type) =&gt; {
      return (val) =&gt; {
        const flag = type === &quot;reject&quot;;
        while (true) {
          const executor = this.executors.shift();
          if (executor) flag ? executor.reject(val) : executor.resolve(val);
          else break;
        }
        return val;
      };
    };
    const handler = {
      get: (target, prop) =&gt; {
        // console.log(prop);
        if (prop === &quot;update&quot;) {
          // return a function which takes the new promise value and its executor as argument
          return (v, executor) =&gt; {
            // console.log(&#39;upd&#39;, v, this.value);
            this.value = v;
            if (executor) this.executors.push(executor);
            // attach `then` function to the new promise, so that the old promises are fulfilled when the new one does
            // this has no effect on already fulfilled promises.
            v.then(
              (val) =&gt; prevResolvers(&quot;resolve&quot;)(val),
              (val) =&gt; prevResolvers(&quot;reject&quot;)(val)
            );
          };
        } else if (typeof this.value === &quot;undefined&quot;) {
          // if value is undefined, i.e. promise was never updated, return default property values
          return typeof target[prop] === &quot;function&quot; ?
            target[prop].bind(target) :
            target[prop];
        }
        // else,  attach functions to new promise
        else if (prop === &quot;then&quot;) {
          //   console.log(&#39;then&#39;, this.value);
          return (onfulfilled, onrejected) =&gt;
            this.value.then(onfulfilled, onrejected);
        } else if (prop === &quot;catch&quot;) {
          return (onrejected) =&gt; this.value.catch(onrejected);
        } else if (prop === &quot;finally&quot;) {
          return (onfinally) =&gt; this.value.finally(onfinally);
        } else return target[prop];
      },
    };
    return new Proxy(prom, handler);
  }
}



const input = document.getElementById(&quot;input&quot;)
const output = document.getElementById(&quot;output&quot;)
const resBtn = document.getElementById(&quot;res&quot;)
const rejBtn = document.getElementById(&quot;rej&quot;)


const ex_1 = {
  resolve: () =&gt; void 0,
  reject: () =&gt; void 0,
};

const prom_1 = new Promise((resolve, reject) =&gt; {
  ex_1.resolve = resolve;
  ex_1.reject = reject;
});

const up = new UpdatablePromise(prom_1, ex_1)

// Await the promise
up.then(_ =&gt; print(_), _ =&gt; print(_))

// Print the value of promise, highlight if it is rejected
async function print() {
  try {
    const val = await up;

    output.innerHTML += `
${val}`

  } catch (e) {
    output.innerHTML += `
&lt;mark&gt;${e}&lt;/mark&gt;`
  }
}


resBtn.addEventListener(&quot;click&quot;, () =&gt; {
  up.update(Promise.resolve(input.value));
  print();
})


rejBtn.addEventListener(&quot;click&quot;, () =&gt; {
  up.update(Promise.reject(input.value));
  print();
})


function consoleTest() {
  const ex = {
    resolve: () =&gt; void 0,
    reject: () =&gt; void 0,
  };

  const prom = new Promise((resolve, reject) =&gt; {
    ex.resolve = resolve;
    ex.reject = reject;
  });

  const up = new UpdatablePromise(prom, ex);

  setTimeout(() =&gt; ex.resolve(&quot;resolved&quot;), 1000);

  up.then(
    (_) =&gt; console.log(_, &quot;res&quot;),
    (_) =&gt; console.log(_, &quot;rej&quot;)
  );

  setTimeout(async() =&gt; {
    up.update(Promise.reject(&quot;reject&quot;));
    up.then(
      (_) =&gt; console.log(_, &quot;res&quot;),
      (_) =&gt; console.log(_, &quot;rej&quot;)
    );
  }, 2000);
  setTimeout(async() =&gt; {
    up.update(Promise.resolve(&quot;res again&quot;));
    up.then(
      (_) =&gt; console.log(_, &quot;res&quot;),
      (_) =&gt; console.log(_, &quot;rej&quot;)
    );
  }, 2500);
}

consoleTest();

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;

&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot; /&gt;
  &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;
  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;
  &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;label for=&quot;input&quot;&gt;Enter a value to update promise with:&lt;/label&gt;
  &lt;input id=&quot;input&quot; /&gt;

  &lt;div&gt;
    &lt;button id=&quot;res&quot;&gt;
        resolve
      &lt;/button&gt;

    &lt;button id=&quot;rej&quot;&gt;
        reject
      &lt;/button&gt;
  &lt;/div&gt;
  &lt;pre id=&quot;output&quot;&gt;&lt;/pre&gt;
&lt;/body&gt;

&lt;/html&gt;

<!-- end snippet -->

JS Fiddle

ts playground - ts version (may not be updated. Prefer fiddle version)

Here's the part that prints the promise's value:

// Print the value of promise, highlight if it is rejected
async function print() {
  try {
    const val = await up;

    output.innerHTML += `
${val}`

  } catch (e) {
    output.innerHTML += `
&lt;mark&gt;${e}&lt;/mark&gt;`
  }
}

PROBLEM:

It seems to work sometimes, for example, in console or in the fiddle.

But doesn't actually work when I use it in the service worker, only the old value of the promise is returned, . I'm using workbox, if that's relevant.

I'm yet to pinpoint the problem. So here's the actual workbox code that doesn't work for me:

// If the refresh Token is resolved, the user is logged in, otherwise not.
class MyStrat extends Strategy {
  async _handle() {
    try {
      await refreshToken;

      return new Response(JSON.stringify({ is_logged_in: true }), {
        status: 200,
        headers: [[CONTENT_TYPE, APPLICATION_JSON]],
      });
    } catch (e) {
      console.log(&#39;error&#39;, e);
      return new Response(JSON.stringify({ is_logged_in: false }), {
        status: 400,
        headers: [[CONTENT_TYPE, APPLICATION_JSON]],
      });
    }
  }
}

PRECISE QUESTION:

I'd like to know a few things:

  1. Does it really work as mentioned above?
    (i.e. It works exactly like a promise, with the exception that it
    can be "reset" and once it is updated, all pending awaits or
    attached callbacks fulfil with the new updated value)

  2. If yes, then what could be the reason that it doesn't work in (workbox's) service worker.

  3. If no, then what's actually happening?

  4. If it really does work, then is it possible to add a state member variable to synchronously keep track of promise state? (I tried it once, didn't work at all)

Edit 2:

Apparently this actually does seem to work in service worker as well. The promise was getting updated to value stored in database repeatedly due to some other functions.

However, I'd still like to get an answer for my other questions

答案1

得分: 1

> Does it really work like I'm expecting it to work in the console or fiddle?

只有你能够判断它是否符合你的期望。但根据你所说,它在控制台、fiddle以及(根据你的编辑)在服务工作线程中都能正常工作,似乎是的。

然而,在这里使用 Proxy 没有充分的理由。如果你使用一个包装了 Promise 的常规类实例,实现会更加清晰:

class UpdatableResource {
  /**
   * @param prom - 默认 promise 对象
   * @param resolver - 可选的解析器函数,用于在更新时解决 promise。
   */
  constructor(prom, resolver) {
    this.value = Promise.resolve(prom);
    this.handlers = [];
    if (resolver) this.handlers.push(resolver);
  }
  /**
   * 调用先前的解析/拒绝函数以满足先前的 promise,如果有的话。
   * 辅助函数,只是为了减少在 `update` 函数中的代码重复。
   */
  _runHandlers(val) {
    while (this.handlers.length) {
      const handler = this.handlers.shift();
      handler(val);
    }
  }
  /* 一个接受新 promise 值及其执行器的函数 */
  update(v, handler) {
    // console.log('upd', v, this.value);
    this.value = Promise.resolve(v);
    // 将旧 promise 解析为新 promise,以便在新 promise 完成时完成旧 promise
    this._runHandlers(v);
    if (handler) this.handlers.push(handler);
  }
  then(onfulfilled, onrejected) {
    return this.value.then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.value.catch(onrejected);
  }
  finally(onfinally) {
    return this.value.finally(onfinally);
  }
}

> Is it possible to add a state member variable to synchronously keep track of promise state?

当然,只需添加以下内容:

this.state = "pending";
this.value.then(() => {
  this.state = "fulfilled";
}, () => {
  this.state = "rejected";
});

在每次将 promise 分配给 this.value 之后(或更好地,将其放入辅助方法中)。

英文:

> Does it really work like I'm expecting it to work in the console or fiddle?

Only you can tell whether it does what you are expecting. But given you say it works, in the console, in the fiddle, and (according to your edit) also in the service worker, it seems that yes it does work.

However, there is no good reason to use a Proxy here. The implementation becomes much cleaner if you use a regular class instance that is wrapping a promise:

class UpdatableResource {
  /**
   * @param prom - the default promise object
   * @param resolver - optional resolver function to resolve the promise when updating.
   */
  constructor(prom, resolver) {
    this.value = Promise.resolve(prom);
    this.handlers = [];
    if (resolver) this.handlers.push(resolver);
  }
  /**
   * Call previous resolve/reject functions to fulfil previous promises, if any.
   * helper function, just to reduce code duplication in `update` function.
   */
  _runHandlers(val) {
    while (this.handlers.length) {
      const handler = this.handlers.shift();
      handler(val);
    }
  }
  /* a function which takes the new promise value and its executor as argument */
  update(v, handler) {
    // console.log(&#39;upd&#39;, v, this.value);
    this.value = Promise.resolve(v);
    // resolve the old promise(s) to the new one, so that the old promises are fulfilled when the new one does
    this._runHandlers(v);
    if (handler) this.handlers.push(handler);
  }
  then(onfulfilled, onrejected) {
    return this.value.then(onfulfilled, onrejected);
  }
  catch(onrejected) {
    return this.value.catch(onrejected);
  }
  finally(onfinally) {
    return this.value.finally(onfinally);
  }
}

> Is it possible to add a state member variable to synchronously keep track of promise state?

Sure, just add

this.state = &quot;pending&quot;;
this.value.then(() =&gt; {
  this.state = &quot;fulfilled&quot;;
}, () =&gt; {
  this.state = &quot;rejected&quot;;
});

after each assignment of a promise to this.value (or better yet, put it in a helper method).

huangapple
  • 本文由 发表于 2023年5月30日 04:15:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定