Notorious
Notorious

Reputation: 3217

React/Javascript - Function returns before finished executing

I have created a function, which accepts an object and parses through to build a search query. The problem I am having is that this function returns before I have looped through the object:

export default function buildQuery(query) {

    let buildQuery = "?", pushAmpersand;
    Object.keys(query).map((v, i) => {
        i === 0 ? pushAmpersand = "" : pushAmpersand = "&";
        buildQuery += pushAmpersand + v + "=" + query[v];
    });

    console.log('Finished executing?');
    console.log(buildQuery);
    return buildQuery;
}

The return value is "?" - from having set the string at the start. Why is it not waiting until I have looped over the object?

I gather this is because it is an "asynchronous" function, so is this the place where I am supposed to introduce a promise, or a callback? It is my first time encountering a problem like this.

Thanks for your answer.

Upvotes: 0

Views: 128

Answers (1)

bennygenel
bennygenel

Reputation: 24680

Rather then using a map you can use Array.prototype.forEach()

export default function buildQuery(query) {    
    let buildQuery = "?";
    Object.keys(query).forEach((v, i) => {
        if( i !== 0 ) buildQuery += "&";
        buildQuery += (v + "=" + query[v]);
    });    
    console.log('Finished executing?');
    console.log(buildQuery);
    return buildQuery;
}

Upvotes: 1

Related Questions