3

I recently started working with JS Promises. What I always like to do, is create function, which returns a Promise with the final desired result, but I only do 1 operation/then. Consider something like this (this fetches the versions of an npm package in an array in reverse order):

function packageVersions(name) {
  return fetchJson(npmUrls.getPackageUrl(name))
    .then(npmPackage => npmPackage.versions)
    .then(versionsObject => Object.keys(versionsObject))
    .then(versions => versions.sort((a, b) => b.localeCompare(a)));
}

Like if I was doing a lots of .maps sequentially.

My question would be: is this considered a good practice in general? Could this have significant perfomance drawbacks, if I do a lots of chaining? Do you consider this unreadable in any way?

Would this be better?

function packageVersions(name) {
  return fetchJson(npmUrls.getPackageUrl(name))
    .then(npmPackage => {
        const versions = Object.keys(npmPackage.versions);
        return versions.sort((a, b) => a.localeCompare(b));
    });
}

closed as primarily opinion-based by Scant Roger, Robert Harvey, Ixrec, GlenH7, user40980 Jan 8 '16 at 2:26

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

0

It potentially could have some performance issues but that probably isn't a big deal. It would be adding an asynchronous "tick" after each then when in this case it doesn't need to.

The big issue to me is that I would assume at first glance that the promise chain calls asynchronous methods even though it doesn't.

Not the answer you're looking for? Browse other questions tagged or ask your own question.