Waiting for Promise API calls to finish [duplicate] - javascript

This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Using async/await with a forEach loop
(33 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Okay, so I have this function that is a simple Axios request. We know that Axios will run as a promise based request so we do something like this and push all the responses into an array
let array = []
function A() {
return axios.get(url).then(r => r.data).then(r => array.push(r.forms))
}
The issue is now I need to call this function specifically 898 times.
async function main() {
await someArrayWithALotOfObjects.forEach(async (e) => {
return await A(e.url);
});
console.log(array);
}
The issue is when I run main() it console logs [], however when I change the main function to be completely hardcoded it outputs all the data correctly pushed to the array in a workable format.
async function main() {
await A(someArrayWithALotOfObjects[0].url);
await A(someArrayWithALotOfObjects[1].url);
await A(someArrayWithALotOfObjects[2].url);
await A(someArrayWithALotOfObjects[3].url);
await A(someArrayWithALotOfObjects[4].url);
await A(someArrayWithALotOfObjects[5].url);
await A(someArrayWithALotOfObjects[6].url);
await A(someArrayWithALotOfObjects[7].url);
...
console.log(array);
}
So my question is how to not hardcode because the loop does not seem to be completed before I run the console.log function.
Note: eventually I will be changing the console logging to the fs event for writing to a file if this helps in writing a better solution.
Note2: IDK how to use the new yield stuff in JavaScript yet, so if that is the solution needed forgive me.

Related

console.log after await doesnt print its content [duplicate]

This question already has answers here:
Async/Await code not being executes after await
(3 answers)
After an await call, it doesn't execute next line [closed]
(1 answer)
Closed 6 months ago.
I read about async/await, but I've a question. I know that await only works with promises, but why in the code below, the last console doesn't print at all!
async function printMe() {
console.log("First")
await new Promise (resolve => {setTimeout(() => console.log("Async!!!"), 3000)})
console.log("Last")
}
printMe()
When using Promise, you need to call the resolve method to fulfil the promise:
async function printMe() {
console.log("First")
await new Promise (resolve => {setTimeout(() => {
console.log("Async!!!")
resolve()
}, 3000)})
console.log("Last")
}
printMe()
N.B: There is also a reject method available, you can find more about it by reading the related MDN page

Javascript await promise in foreach [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Closed 9 months ago.
Hello im trying to loop throught an array with the
I tried to make the forEach loop Async
content.forEach(asnyc(element) => {
console.log(func(element)
})
This gave me a syntax error stating that it expects a ,
forEach statement like this
content.forEach(element => {
console.log(func(element)
})
The func will return a promise and currently I need to find a way to await it
the function this code is running in is Async
And im perfectly able to await a promise in it
However in a forEach loop it doesnt seem to work
I tried to do the following
content.forEach(element => {
console.log(await func(element)
})
SyntaxError: await is only valid in async functions and the top level bodies of modules
I tried to make the forEach loop Async
content.forEach(asnyc(element) => {
console.log(func(element)
})
This gave me a syntax error stating that it expects a ,

Javascript: How to wait for fetch result before continuing [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
This question may have been asked here before, and I'm sorry, but I wasn't able to find a solution to my problem anywhere. I am relatively new to JavaScript and things like "promises" are alien to me. I am trying to make a code that will load an array from a .JSON file, and after it loads, the code will continue.
async function fetchTags() {
var response = await fetch('../json/tags.json');
var json = await response.json();
console.log(json); // returns: Array()
return json;
}
function mainFunction() {
let tags = fetchTags();
console.log(tags); // returns: Promise { <state>: "pending" }
}
This is what my current code looks like, using a not-working "solution" I found on the internet. While the console.log(json), which is inside of the async function, returns the array correctly, the main function's console.log(tags) displays this promise with a "pending" state - and displays sooner than the array can be loaded, if I understand correctly.
The following code of the mainFunction() however relies strongly on this array, and it should not proceed before the array is loaded. Where am I making a mistake?
Thanks a lot for all your replies.
At this point, fetchTags is an asynchronous function and needs to be treated as such when calling it. You have two implementation options here:
Use async/await for your mainFunction function:
async function mainFunction() {
let tags = await fetchTags()
console.log(tags)
}
Appropriately handle the promise that is returned by the function:
function mainFunction() {
fetchTags()
.then(console.log)
.catch(console.error)
}

how to wait for all requests to complete before doing the next action (fetch) [duplicate]

This question already has answers here:
How to use fetch within a for-loop, wait for results and then console.log it
(5 answers)
Closed 2 years ago.
I go through all the elements of the array and form a request for each, how can I display a success message only after all requests have been completed?
saveAllPages() {
const allStagesData = JSON.parse(JSON.stringify(this.data.pages)).map(el => {
const id = el.id
apiService.postCurrentScript(el, id)
??? alert('success')
}
Maybe I should use Promise all, but how implement it here?
I would suggest using async-await as it makes code cleaner. Async-await is just an alternaitive to using promises and is many times considered a better choice. I have converted your function into arrow function. The implementation is given below:
saveAllPages = async () => {
const allStagesData = await (function which returns promise);
if(allStagesData){
alert("success");
}
}
saveAllPages();

Single async function that makes multiple fetches and returns results? [duplicate]

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 4 years ago.
I am attempting to write an async function that makes multiple fetches, waits for all to complete, then returns the JSON results as an array. This is what I have so far:
file1.js
const searchResults = await Api.search(searchText);
api.js
async function search(searchText) {
return util.executeFetchAll([
`/searchA/${searchText}`,
`/searchB/${searchText}`,
`/searchC/${searchText}`
]);
}
util.js
async function executeFetchAll(urls) {
const promises = urls.map(url => fetch(url));
const responses = await Promise.all(promises);
debugger;
}
When execution pauses at the debugger and I inspect responses using Chrome's dev tools, it is correctly an array of 3 Response objects, but if I inspect responses[0].json(), it weirdly returns in the console a Promise {<pending>} object.
What am I missing? I'm awaiting Promise.all, which should mean all promises resolve before my debugger line. So why is the json() method weirdly showing a Promise object in a pending state?
Thanks.
response.json() return a Promise! see: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
So you can await them with something like this:
await Promise.all(responses.map(r => r.json()));

Categories

Resources