英文:
Updatable promises using proxy in JavaScript
问题
PROBLEM:
似乎在某些情况下起作用,例如在控制台或JSFiddle中。但当我在服务工作者中使用它时实际上不起作用,只返回承诺的旧值。我正在使用Workbox,如果相关的话。
PRECISE QUESTION:
我想知道一些事情:
- 它是否真的像上面提到的那样工作?(即它的工作方式与Promise完全相同,唯一的例外是它可以被“重置”,一旦更新,所有挂起的
await
或附加的回调都会履行为新的更新值) - 如果是,那么在(Workbox的)服务工作者中它为什么不起作用的原因是什么?
- 如果不是,那么实际上发生了什么?
- 如果它确实起作用,那么是否可能添加一个
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) => {
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();
<!-- language: lang-html -->
<!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>
<!-- end snippet -->
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:
-
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 pendingawait
s or
attached callbacks fulfil with the new updated value) -
If yes, then what could be the reason that it doesn't work in (workbox's) service worker.
-
If no, then what's actually happening?
-
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('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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论