0

Considering all job1, job2, job3 and job4 return promises, what is the difference between apart from nuances of code readability. What does test() return in either case? Let's say doSomething() is a heavy async operation, should chaining be used or first method be used?

function test() {
    return job().then(function() {
        return job2().then(function() {
            return job3().then(function() {
                return job4().then(function() {
                    doSomething();
                });
            });
        });
    });
}

and

function test() {
    return job()

    .then(function() {
        return job2();
    })

    .then(function() {
        return job3();
    })

    .then(function() {
        return job4();
    })

    .then(function() {
        doSomething();
    });
}
alchemist95
  • 759
  • 2
  • 9
  • 26
  • The last `then` is not returning anything... So in both cases, I guess `test()` returns `undefined`. Could you post some code that is more *complete* than *minimal* ? – Louys Patrice Bessette Sep 05 '21 at 16:55
  • "*Let's say doSomething() is a heavy async operation*" - then why does it not return a promise like the `jobN` functions do? – Bergi Sep 05 '21 at 17:37
  • [They're equivalent](https://stackoverflow.com/a/22000931/1048572) – Bergi Sep 05 '21 at 19:07
  • The question does not reflect what is normally understood by [breaking a promise chain](https://stackoverflow.com/a/28250704/3478010). – Roamer-1888 Sep 06 '21 at 01:43
  • One of the benefits we get from the Promise interface is that it resolves "callback hell". You can still visit that hell *with* promises... but why should you? – trincot Sep 06 '21 at 10:34

1 Answers1

2

In each method the jobs will be run in the same order, and the function test will return a promise that resolves with undefined (however, if your code is meant to return doSomething(), then test will return a promise with the value from doSomething in both cases). And as far as I can see, there is no significant performance different between the 2. Either solution seems optimal, and it would just be a question of preference.

The same result is also created by using the async/await keywords.

async function test() {
  await job()
  await job2()
  await job3()
  await job4()
  await doSomething()
  // or `return await doSomething()` if you are suppose to return the value
}
The Otterlord
  • 1,680
  • 10
  • 20