My first suggestion would be to declare variable names that match the response object:
const items = response.items;
Then assuming your API has a sensible naming convention - i.e. a plural for groups of elements - you can use the singular in your iteration. But you should consider looping with an Array method instead; because then you can get rid of a lot of the temporary variables:
response.items.forEach(item => {
// do stuff with each item
});
I should add that typically your API call will be async so you would expect to either use a Promise or an await there ;)
You would also usually add a guard to make sure you have a response to work with.
A software engineer interested in solving real problems, developer productivity & learning languages for fun. Primarily working on Node.js, React & databases. Current Interest: Rustlang
Thanks Ben. I do understand that using array methods would make reduce the no. of temporary variables. I've kept it simple enough so that people coming from any language would understand. That's the reason I have removed await as well.
Also if it's in JavaScript, we may have to use something like bluebird to ensure all api calls are complete.
Also there are some instances where I'd like to have multiple tokens as in previous example. I will have a token for foo call, another for each of the api call for bar.
It can essentially become something like:
1 foos -> 1 bar requests(at least) -> 1 bar request can have multiple pages to query for.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
My first suggestion would be to declare variable names that match the response object:
const items = response.items;
Then assuming your API has a sensible naming convention - i.e. a plural for groups of elements - you can use the singular in your iteration. But you should consider looping with an Array method instead; because then you can get rid of a lot of the temporary variables:
I should add that typically your API call will be async so you would expect to either use a Promise or an
await
there ;)You would also usually add a guard to make sure you have a response to work with.
Thanks Ben. I do understand that using array methods would make reduce the no. of temporary variables. I've kept it simple enough so that people coming from any language would understand. That's the reason I have removed await as well.
Also if it's in JavaScript, we may have to use something like bluebird to ensure all api calls are complete.
Also there are some instances where I'd like to have multiple tokens as in previous example. I will have a token for foo call, another for each of the api call for bar.
It can essentially become something like:
1 foos -> 1 bar requests(at least) -> 1 bar request can have multiple pages to query for.