0

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.

7
  • You're using map incorrectly. It's not a replacement for a normal loop. map should return values into a new array. Try forEach instead. Commented Sep 24, 2017 at 8:46
  • Based off many other answers (e.g: stackoverflow.com/questions/40950546/…) this is a valid way to loop through an object in React to retrieve key value pairs. This has nothing to do with why my function is returning before it is finished. Commented Sep 24, 2017 at 8:51
  • And I'm telling you you're using map incorrectly. Look at that example in the link you provided. map is returning a value to create a new array. Did you at least try forEach? Commented Sep 24, 2017 at 8:53
  • @Andy it should still make buildQuery as buildQuery += pushAmpersand + v + "=" + query[v] will execute inside the callback function everytime. Commented Sep 24, 2017 at 8:54
  • 1
    Ahh dammit, so sorry guys but thanks Djj your comment has had me realise what I am passing is an empty object. I am passing through an object I have just setState with, looks like state has not updated before I sent this.state.query as an argument to the function call. Also thanks for your comments Andy, I will look more into the differences between map and forEach as yes I am probably using the wrong one. Thanks for your comments. Commented Sep 24, 2017 at 8:59

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.