Consider the following code:
function main() {
console.log('START');
test('A');
test('B');
console.log('END');
}
function waitForSomething(label) {
return {
then(onFulfilled) {
console.log(`FULFILL: ${label}`);
onFullfilled();
}
}
}
async function test(label) {
console.log(`BEFORE: ${label}`);
await waitForSomething(label);
console.log(`AFTER: ${label}`);
}
It gives the following output:
START
BEFORE: A
BEFORE: B
END
FULFILL: A
FULFILL: B
AFTER: A
AFTER: B
I would like AFTER A
to trigger immediately after FULFILL A
, in a synchronous way. The idea is that I’m writting a library with a global state that I want to stay consistent accross a chain of asynchronous calls written by the user. Because multiple chains may be running at the same time, I need to run some code before a call chain “resumes”. I understand it may seem like a weird or bad idea at first glance, but this is a separate question. Is there a way to do that?
I’ve thought of returning an object with something like an unwrap
method that would trigger the code, like:
(await waitForSomething(label)).unwrap();
But this forces the user to use unwrap()
on all relevant calls, which is tedious. Moreover they may forget to do it and run into unexpected issues without understanding why.
symil is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.