What's the best way to iterate over results from an APi, and know when it's finished?
You can use DispatchGroups
. It will trigger an async callback block when all your requests are completed.
DispatchGroup:
DispatchGroup allows for aggregate synchronization of work. You can
use them to submit multiple different work items and track when they
all complete, even though they might run on different queues. This
behavior can be helpful when progress can’t be made until all of the
specified tasks are complete.
In your code, it would like this:
// ...
// Create the DispatchGroup:
let dispatchGroup = DispatchGroup()
for thisFoodId in foodIds {
// Enter the DispatchGroup:
dispatchGroup.enter()
// ...
let task = session.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in
// ...
do {
// ...
if tracker == foodIds.count {
// Leave the DispatchGroup
dispatchGroup.leave()
}
}
})
// When all your tasks have completed, notify your DispatchGroup to run your work item:
dispatchGroup.notify(queue: DispatchQueue.main, execute: {
// All your async requests are finished here, do whatever you want :)
})
}
API and loop iteration values not matching
I want to splice or remove the values that are submitted successfully from the object and keep the ones that aren't. I also want to set some type of delay or timeout between each iteration to the API calls to I'm not hitting the API with each call all at one time.
Is there a reason you need to splice and remove values? What if you keep the form item in the array and use a data structure that includes the state of the form?
[
{
form: {...},
status: "pending" // or "invalid" or "submitted" etc
},
...
]
If you follow this design you can iterate over the forms in different ways and multiple times without causing errors.
How to iterate using iterator over API object using JavaScript?
You're calling getCV()
which does repeat the request and create a new iterator every time you click the element. It sounds like what you actually want to do is
const iteratorPromise = getCV();
iteratorPromise.catch(console.error);
next.addEventListener('click', function nextCV(e) {
iteratorPromise.then(iterator => {
const a = iterator.next().value;
console.log(a); // or DOM manipulation
});
});
or
getCV().then(iterator => {
next.addEventListener('click', function nextCV(e) {
const a = iterator.next().value
console.log(a); // or DOM manipulation
});
}).catch(console.error);
How do I iterate through and append the data from multiple pages with an API request?
You can make the pagination with the help of payload along with for loop and range function
import requests
url = "https://indeed11.p.rapidapi.com/"
payload = {
"search_terms": "data visualization",
"location": "New York City, NY",
"page": 1,
"fetch_full_text": "yes"
}
headers = {
"content-type": "application/json",
"X-RapidAPI-Key": "{api key here}", # insert here,
"X-RapidAPI-Host": "indeed11.p.rapidapi.com"
}
for page in range(1,11):
payload['page'] = page
response = requests.post(url, json=payload, headers=headers)
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
I use a for loop to iterate the string and use charAt()
to get each character to examine it. Since the String is implemented with an array, the charAt()
method is a constant time operation.
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
That's what I would do. It seems the easiest to me.
As far as correctness goes, I don't believe that exists here. It is all based on your personal style.
Best way to wait for .forEach() to complete
If there is no asynchronous code inside the forEach
, forEach
is not asynchronous, for example in this code:
array.forEach(function(item){
//iterate on something
});
alert("Foreach DONE !");
you will see the alert after forEach
finished.
Otherwise (You have something asynchronous inside), you can wrap the forEach
loop in a Promise:
var bar = new Promise((resolve, reject) => {
foo.forEach((value, index, array) => {
console.log(value);
if (index === array.length -1) resolve();
});
});
bar.then(() => {
console.log('All done!');
});
Credit: @rolando-benjamin-vaz-ferreira
Is it possible to iterate over a tree and indent the results by level with reduce() ?
You can achieve that with a helper method which takes a “level” parameter and calls itself recursively on each child node with an increased level:
private func toString(level: Int) -> String {
String(repeating: " ", count: level) + "\(value)"
+ children.reduce("") { $0 + "\n" + $1.toString(level: level + 2) }
}
var description: String {
self.toString(level: 0)
}
How to iterate over a JavaScript object?
For iterating on keys of Arrays, Strings, or Objects, use for .. in
:
for (let key in yourobject) {
console.log(key, yourobject[key]);
}
With ES6, if you need both keys and values simultaneously, do
for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}
To avoid logging inherited properties, check with hasOwnProperty :
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
You don't need to check hasOwnProperty
when iterating on keys if you're using a simple object (for example one you made yourself with {}
).
This MDN documentation explains more generally how to deal with objects and their properties.
If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use
let keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]
:
for (let i=300; i < keys.length && i < 600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
What's the fastest way to loop through an array in JavaScript?
After performing this test with most modern browsers:
https://jsben.ch/wY5fo
Currently, the fastest form of loop (and in my opinion the most syntactically obvious).
A standard for-loop with length caching
var i = 0, len = myArray.length;
while (i < len) {
// your code
i++
}
I would say, this is definitely a case where I applaud JavaScript engine developers. A runtime should be optimized for clarity, not cleverness.
Related Topics
Is the Swift Divide "/" Operator Not Working or Have I Missed Something
How to Bring Nswindow to Front and to the Current Space
How to Convert Anyclass to a Specific Class and Init It Dynamically in Swift
How to Change Navigationbar Font in Swift
Using Scenekit in Swift Playground
Swift 3 - Uibutton Adding Settitle from Plist and Database
Get Bogus Value When Execute Break Point in a Variable
How to Make a Button Have a Rounded Border in Swift
Converting Url to String and Back Again
Default Optional Parameter in Swift Function
What Is the Swift Equivalent of -[Nsobject Description]
Animate Cell When Pressed Using Swift 3
How to Print Call Stack in Swift