English 中文(简体)
Updatable promises using proxy in JavaScript
原标题:

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.

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) => {
      return (val) => {
        const flag = type === "reject";
        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) => {
        // console.log(prop);
        if (prop === "update") {
          // return a function which takes the new promise value and its executor as argument
          return (v, executor) => {
            // console.log( upd , 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) => prevResolvers("resolve")(val),
              (val) => prevResolvers("reject")(val)
            );
          };
        } else if (typeof this.value === "undefined") {
          // if value is undefined, i.e. promise was never updated, return default property values
          return typeof target[prop] === "function" ?
            target[prop].bind(target) :
            target[prop];
        }
        // else,  attach functions to new promise
        else if (prop === "then") {
          //   console.log( then , this.value);
          return (onfulfilled, onrejected) =>
            this.value.then(onfulfilled, onrejected);
        } else if (prop === "catch") {
          return (onrejected) => this.value.catch(onrejected);
        } else if (prop === "finally") {
          return (onfinally) => this.value.finally(onfinally);
        } else return target[prop];
      },
    };
    return new Proxy(prom, handler);
  }
}



const input = document.getElementById("input")
const output = document.getElementById("output")
const resBtn = document.getElementById("res")
const rejBtn = document.getElementById("rej")


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

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

const up = new UpdatablePromise(prom_1, ex_1)

// Await the promise
up.then(_ => print(_), _ => 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 += `
<mark>${e}</mark>`
  }
}


resBtn.addEventListener("click", () => {
  up.update(Promise.resolve(input.value));
  print();
})


rejBtn.addEventListener("click", () => {
  up.update(Promise.reject(input.value));
  print();
})


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

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

  const up = new UpdatablePromise(prom, ex);

  setTimeout(() => ex.resolve("resolved"), 1000);

  up.then(
    (_) => console.log(_, "res"),
    (_) => console.log(_, "rej")
  );

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

consoleTest();
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <label for="input">Enter a value to update promise with:</label>
  <input id="input" />

  <div>
    <button id="res">
        resolve
      </button>

    <button id="rej">
        reject
      </button>
  </div>
  <pre id="output"></pre>
</body>

</html>

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 += `
<mark>${e}</mark>`
  }
}

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( error , 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

问题回答

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( upd , 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 = "pending";
this.value.then(() => {
  this.state = "fulfilled";
}, () => {
  this.state = "rejected";
});

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





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签