I recently started working with JS Promise
s. 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));
});
}