0

I have a function that receives an array of usernames. For each one I need to get the connections IDs and concatenate into another array. But I think the way I did have some problems of race condition that may colide and concatenate less results that it should...

const getConnections = async function (usernames) {

    let connections = [];

    await Promise.all(usernames.map(async (username) => {

        try {

            let connsFound = await dynamo.getConnectionsByUsername(username);

            if (connsFound && connsFound.length > 0)
                connections = connections.concat(connsFound);

        } catch (error) {
            console.error('ERROR GET CONNECTIONS', error)
        }

    }));

    return connections;

};

the result of the connections its an array, so the result I would like to merge to the var connections...but .concat does not merge, it creates a new array, so I need to do a 'var = var.concat(newArray)'

I am affraid this is not safe and in some operation it will colide and overwrite some results...

Is there a better way to do it?

cheers

1
  • return connsFound; instead, and use let connections = await Promise.all(... (Promise.all will resolve to an array of the Promise results, in the same order, which is exactly what you want in the first place, there's no need to concat anything here) Commented Jan 17, 2021 at 16:40

1 Answer 1

2

JavaScript is single threaded, so there is always at most one function that runs and accesses connections. You shouldn't have any problems.

However, there is no reason to do it that way. Since you are already using async/await, you can just create an array of arrays and flatten that:

const getConnections = async function (usernames) {
    const connections = await Promise.all(usernames.map(async (username) => {

        try {
            return await dynamo.getConnectionsByUsername(username);
        } catch (error) {
            console.error('ERROR GET CONNECTIONS', error);
            return [];
        }

    }));
    return connections.flat();
};

.flat is relatively new, but it should be easy to write a custom helper function to achieve the same.

Sign up to request clarification or add additional context in comments.

5 Comments

you do not need return await inside the try/catch -- just return the promise directly
@Joe Then you can't handle the rejection.
You can do return dynamo.getConnectionsByUsername(username).catch((e) => { ... })
@Joe actually, that try-catch block it's useless, but that's the OP's approach.
@Joe I know, but that's different to your initial suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.