Javascript await promise in foreach [duplicate] - javascript

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 ,

Related

I am getting an error is 'await' has no effect on the type of this expression inside an it block [duplicate]

This question already has answers here:
Verify that an exception is thrown using Mocha / Chai and async/await
(14 answers)
Closed 29 days ago.
I am getting a failed result in test cases which is caused by an await keyword not taking effect.
The warning i am getting is 'await' has no effect on the type of this expression.ts(80007)
and the code for that function which uses chai library is
describe("Add Task", function() {
it("Should emit AddTask Event", async () => {
let task = {
'taskText':"New task",
'isDeleted': false,
};
await expect(taskContract.addTask(task.taskText, task.isDeleted)
.to.emit(taskContract,"AddTask")
.withArgs(owner.address,total_tasks));
});
});`
I tried making the async function a normal function without arrow but it does'nt work.
That's because expect doesn't return a promise, but only promises can be awaited
Remove await and async

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

Waiting for Promise API calls to finish [duplicate]

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.

Promises in Promise.all() return undefined sometimes / crawler-request package nodejs [duplicate]

This question already has answers here:
Promise.all is returning an array of undefined and resolves before being done
(3 answers)
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 26 days ago.
Im not sure if im using promise.all wrong, or if the nodejs package I use for retrieving pdf remotly and parsing these is overwhelmed by too many requests at once.
https://codesandbox.io/s/sharp-wave-qikvb // here the codesandbox
I attempted to use promise.all
let urls = [arrayofURLS];
function pdfData() {
return Promise.all(
urls.map(item => {
this.crawlPdf(item);
})
)
.then(result => {
// handle result
})
}
This is the function that uses the crawler package (called crawler-request) :
crawlPdf: async function(Url) {
return new Promise(async function(resolve, reject) {
let response = await crawler(Url);
resolve(response.text);
}
2 out of 5 requests are usually undefined.
But sometimes everything works o.O..
You must return promises to the all method. Right now you aren't returning anything so it looks like Promise.all([undefined, undefined, undefined])
Since it looks like you can use arrow functions, you can just switch your curly brackets for parens, or put it on one line and get rid of the brackets completely - these formats always return the result of the function body.
urls.map(item => (
this.crawlPdf(item)
));
urls.map(item => this.crawlPdf(item));
Or keep it explicit
urls.map(item => { return this.crawlPdf(item) });

Creating better version of promise function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
Im a bit struggling to grasp promises, I have a use case when I perform X async actions, and when these are completed I make call to rest api. below my code:
const promises = defect.images.map(async image => {
return new Promise((resolve)=> {
this.fileProvider.getDefectImage(image.url)
.then(binary => {
images.set(image.url, binary);
resolve();
});
})
});
console.log(images)
return Promise.all(promises)
.then(() => spinner.dismiss())
but the console.log of images is always empty ... what should i change?
//edit
sorry guys for leading into a trap, indeed this console.log can not work properly but Im not getting the data on bakcend side, its also empty there.
You are logging images before any of the promises have been resolved, so it's still empty at that point.
You need to wait for all the promises to be resolved first. And apparently you already know how to do that:
return Promise.all(promises)
.then(() => {
console.log(images);
spinner.dismiss();
})
Besides, you are mixing async/await syntax and Promise syntax. If you're going to rely on async/await, you might as well go all the way, and then your code will be executed from top to bottom again:
const promises = defect.images.map(async image => {
let binary = await this.fileProvider.getDefectImage(image.url);
images.set(image.url, binary);
});
await Promise.all(promises);
console.log(images);
spinner.dismiss();

Categories

Resources