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 :

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

Leave a Reply