Home > database >  Create promised function to sort by name and then chain it
Create promised function to sort by name and then chain it

Time:01-12

Create another promisified function that sorts this employee list from below response by name. Chain it to below promise

function arr() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve(employeeDetailsArray);
        }, 2000);
    });
}

arr()
.then(function(result) {
    console.log(result); 
    return arr();
})
.then() ////code to sort by name, output should be sorted list of employee details by name

const employeeDetailsArray = [
  { name: 'boss', email: '[email protected]', age: 22 },
  { name: 'avid', email: '[email protected]', age: 60 },
  { name: 'rajam', email: '[email protected]', age: 75 },
  { name: 'dam', email: '[email protected]', age: 45 }
]

output should be :-

//after 2 seconds(this is done)


       const employeeDetailsArray = [
      { name: 'boss', email: '[email protected]', age: 22 },
      { name: 'avid', email: '[email protected]', age: 60 },
      { name: 'rajam', email: '[email protected]', age: 75 },
      { name: 'dam', email: '[email protected]', age: 45 }
    ]

//then it should print same array in sorted order by name(this is remaining)

    const employeeDetailsArray = [
      { name: 'avid', email: '[email protected]', age: 60 },
      { name: 'boss', email: '[email protected]', age: 22 },
      { name: 'dam', email: '[email protected]', age: 45 }, 
      { name: 'rajam', email: '[email protected]', age: 75 },
      ]

CodePudding user response:

To do this, you could write a new function sortByName(array) like this:

function sortByName(array) {
  return array.sort((a, b) => {
    if (a.name < b.name) {
      return -1;
    }
    if (a.name > b.name) {
      return 1;
    }
    return 0;
  });
}

This sorts the array by name. This could also be minimized to:

function sortByName(array) {
  return array.sort((a, b) => {
    return a.name > b.name ? 1 : -1;
  });
}

With the same functionality in this case.

You could then call it using:

arr().then(function(result) {
  console.log(result);
}).then(function (result) {
  console.log(sortByName(result));
})

This should achieve your desired result. Why does this work?

You can chain .then() and .catch() multiple times. The code blocks will execute one after another. Please also keep in mind that returning something from .then(function(data)) could have undesired effects, as .then() returns a promise and not the data itself directly. Please read more about it at this article.

  • Related