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.
mapincorrectly. It's not a replacement for a normal loop.mapshould return values into a new array. TryforEachinstead.mapis returning a value to create a new array. Did you at least tryforEach?buildQuery += pushAmpersand + v + "=" + query[v]will execute inside the callback function everytime.