Suggest .then promise chain can carry states

This is what i want to do, the 3rd line in the pseudo code gets response from the request. Then i want to update the original request with the response data like the 4th line, is there any way i can do it ?

await Promise.resolve(buildReq(input))
.then((req) => httpPost(req))
.then((res) =>
.then((req, resData) => _.update(req, 'field1', ()=>resData));

Here resData is from line 3, req is from line 1.

Yes - by resisting the impulse to chain, and to use await.

const req = buildReq(input);
const res = req.then(httpPost);
const [req, { data }] = await Promise.all([req, res]);
_.update(req, 'field1', () => data));

An alternative, since everything does depend on each other (which means a chain is appropriate):

const req = await buildReq(input);
const { data } = await httpPost(req);
_.update(req, 'field1', () => data));

1 Like

Yes i totally understand it can be solved by promise.all and other ways, but the goal is to enhance Javascript language :grinning:

The second example I provided seems pretty straightforward without the need for any language changes.


Many, actually. I've counted 5 so far.
async/await is the most intuitive of them and provided natively by the language. then should not carry any "state", that would lead to lots of memory (and security) leaks. We would need to introduce a new method for this (e.g. promise.keepAndThen(…).then(both => …})) and it would still be a nuisance.

Totally understand the challenge, but i'm just wishing there's a simple way, e.g. if the input variables of a .then statement does show up before, then we can treat it as local variable.

So in my original code, line 2 has req as input, line 4 has it again. If we treat this .then chain as a function, req is like a local variable within the scope of this function.

Now we do need to exercise all cases to see if this can work or not.
Just throwing some idea hopefully can make JS more powerful. If not, at least i tried :grinning:

JS already has that power. Treat your promise sequence as a function by making it an async function, and req becomes an actual local variable.

If you suggest that we actually treat .then chains differently in the language, i.e. change the semantics so that your exact example statement will work as you suggest, we cannot do that - it would break existing code. If we try to come up with a new, better syntax that achieves your goal, after exercising all cases we will end up with async/await.

ok, fair enough, thx very much for the info !