1

So the question is pretty straight forward - should .then return last promise inside the body of the function?

For example:

Promise.resolve().then(function() {
  Promise.resolve(1)
  Promise.resolve(2)
}).then(function(val) {
  return val;
})

Should it return last value (2) when promise resolves?

I'm working with some legacy code and this construction is pretty common among some modules, but it doesn't work.

Src
  • 5,252
  • 5
  • 28
  • 56
  • It is unclear what this code is supposed to do. – Quentin Jul 31 '18 at 15:31
  • 1
    Your code does not make much sense, but you need to return somethign from the first `then` so that it will be resolve to the `val` of the second `then`. So if you write `return Promise.resolve(2)` then `val` will be `2`, but `Promise.resolve(1)` will be a _dangling_ Promise that is not part of the chain. It is not really clear what you want to ask with this arbitary example. – t.niese Jul 31 '18 at 15:32
  • @t.niese exactly. So there is nothing like implicit return in such cases, right? – Src Jul 31 '18 at 15:33
  • 2
    Yes there is no implicit return, if you want to wait for two Promises you would write `Promise.all([promiseA, promiseB]).then(function(results) {})` or use `await`/`async`. – t.niese Jul 31 '18 at 15:35

2 Answers2

1

This shouldn't work because the first then returns a promise of undefined.

Maybe you should take a look at Promise.all() https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Fabio Carpinato
  • 1,121
  • 6
  • 13
0

Should .then return the last promise inside the body of the function?

No. A function (including a then callback) should return all promises inside its body. That is, unless you explicitly want to ignore some of them.

Of course, a function can only return a single value, so it can only return one promise. If you are doing multiple things, either do them one after the other and chain your promises, or do them at once and then make a promise that waits for all results using Promise.all.

Also notice that .then(function(val) { return val; }) is pointless and should be dropped.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375