0

I am trying to sort names in two different array. but when I need to return the final result, it will just return the values first then do the forEach.

    const available = [];
    const taken = [];

    const names = data.split('\n');

    names.forEach(async (name, i) => {

            (data.success !== undefined) ? (availabe.push(name)) : (taken.push(name));

    });
    return {   //This returns 0 for both
        available: available.length,
        taken: taken.length
    }
HaMoOoOd25
  • 87
  • 1
  • 2
  • 10

2 Answers2

1

The issue is that forEach doesn't wait for async code. Check here: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

Try this instead:

async function f() {
    const available = [];
    const taken = [];

    const names = data.split('\n');

    for (const name of names) {
        // await request...
        (data.success !== undefined) ? (availabe.push(name)) : (taken.push(name));
    }

    return {   //This returns 0 for both
        available: available.length,
        taken: taken.length
    }
}

Then, when you call f(), make sure you await f().


Side note: if you have very many names, this could get very slow. You're waiting for each request to complete before beginning the next one. You'll want to look into requesting all the data at once, either with a different http endpoint, or using something like Promise.all() or the async library.

Benjamin
  • 1,372
  • 2
  • 12
  • 20
-1

The variable name "available" is misspelled as "availabe" in line 8. Other syntax errors may exist; you might try using something link jslint.com.

Mophilly
  • 143
  • 10