Hi. I need a function to make sure forEach is completed in JavaScript.
Simply I created this function;
Object.defineProperty(Array.prototype, "asyncForEach", {
enumerable: false,
value: function(task){
return new Promise((resolve, reject) => {
this.forEach(function(item, index, array){
task(item, index, array);
if(Object.is(array.length - 1, index)){
resolve({ status: 'finished', count: array.length })
}
});
})
}
});
I use this function like below;
homePage.disabled = true
orders.asyncForEach(function (order) {
api.sendOrder(order)
}).then(function (data) {
homePage.disabled = false
})
This function works as I expect.
So friends, do you know any other ways? Is this an optimized way to catch async operations are completed?
Top comments (5)
You have over overengineered this and your solution wasn't really working as it should.
Yes, This is definitely the solution! Node has native support for dealing with multiple async promises.
You could even remove the variable assignment (though JS is going to assign it to a temp anyways);
Thats if
sendOrder
does not need its functional context. Semantically the same solution, though.I've come up with this solution:
I wouldn't say your approach is not optimized, it looks fine to me. I have to mention that I'm not very experienced though, so I'm not sure my opinion is 100% accurate.
I hope this was helpful to you in some way.
With MojiScript I have created an async
map
,filter
andreduce
to make things like this cake.Check it out here: mojiscript.js.org/#/list-map
Also related: Why async code is so damn confusing (and a how to make it easy)