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));
    });
}

1 Answers1

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.

pllee
  • 1,212
  • 1
  • 9
  • 13