Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript sort requiring async call

I want to sort ids which should return ["b", "a"] in a contrived example point is read below is imposed to be async in real code. I tried this but can’t make prevent it to wait for comparison to finish whereas I wait with then :

  async function test(a, b) {
    return await (async (a, b) => {
      let retval;
      let text_a = await read("a");
      let text_b = await read("b");
      retval = (text_a.length - text_b.length);
      return retval;
    })(a, b);
  }

  let ids = ["a", "b"]

  ids = ids.sort(
    function f(a, b) {
      let retval = test(a, b).then(result => result);
      return retval;
    }
  );
  console.log(ids)

  async function read(p) {
    if(p == "a") {
      return "aaaaaaaaaaaaaaaaa";
    }
    if (p == "b") {
      return "bbbbbbbb";
    }
  }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The sort test function potentially gets called many more times than there are values in the array. Therefore, you’d want to retrieve all values from the read function first.

Even if performance was not a problem, array.sort does not support an async test function.

async function read(p) {
  if(p === 'a') return 'aaaaaaaaaaaaaaaaa';
  if (p === 'b') return 'bbbbbbbb';
}

(async () => {
  let ids = ['a', 'b'];
  (await Promise.all(ids.map(id=>read(id))))
    .forEach((v,i) => ids[i] = {id:ids[i], v});
  ids = ids.sort((a,b) => a.v.length - b.v.length).map(i=>i.id);
  console.log(ids);
})();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading