Implement async / wait in javascript array sort function

I am trying to implement a sorting method on a transporter ElementArrayFinder. As you know, all protractor methods return promises. Therefore, my sorting method has a condition depending on the resolution of promises. I use the node plugin for async/awaitto make it compatible with node.js versions below 6. (Here the plugin: https://www.npmjs.com/package/asyncawait )

Here is my code where this- ArrayElementFinder:

var asyncCompare = async(function(a, b) {
    let x = await (a.getText());
    let y = await (b.getText());
    console.log(x.localeCompare(y));
    return x.localeCompare(y);
});

var sortTheArray = async(function(arrayOfElementFinders) {
    return await (arrayOfElementFinders.sort(asyncCompare));
});

this.then((elements) => {
    let arrayOfElementFinders = [elements[0], elements[1], elements[2]];
    let sortedArray = sortTheArray(arrayOfElementFinders);
    console.log('array sorted');
});

Unfortunately, the timing is not the one I expect. Printing: array sortedoccurs earlier than comparison prints x.localeCompare(y). Any idea what I'm doing wrong? And any idea how to achieve my goal?

Thanks so much for any help

+4
2

sort . , ; , . ( - ).

. - . . Schwartzian, , (), .

const elements = await this;
const arrayOfElementFinders = elements.slice(0, 3); // or Array.from?
const comparableArray = await Promise.all(arrayOfElementFinders.map(async x => [await x.getText(), x]));
comparableArray.sort((a, b) => +(a[0] > b[0]) || -(a[0] < b[0]));
const sortedArray = comparableArray.map(x => x[1]);
console.log('array sorted');
+4

promises V6?

await promise. ?

Promise.all([Promise.resolve(10), Promise.resolve(4), Promise.resolve(7)])
       .then(r => r.sort((a,b) => a-b))
       .then(s => console.log(s));
Hide result

ans splatter .catch() ?

0

Source: https://habr.com/ru/post/1683615/


All Articles