I know Array.prototype.map
is a synchronous operation. On the other hand if the map function is a callback function (asynchronous) undefined
will return immediately.
So my question is can the next function safely assume all callback functions have been done?
A sample code may make my question more clear :
results = files.map(file => {
fs.readFile(file, (err, data) => {
if (err) throw err;
return process(file) //will return the processed value, NOT a promise
});
)
//I know results will be [undefined, undefined, undefined ...]
//But can I assume all the files have been processed if I reach here?
console.log('done')
I don't care about the return values. That is why I don't want to bother with await/async
. I just want to make sure all callback functions have called and returned. Is that possible ?
------- update --------
In additional to the answer I found these articles also help me understand the problem:
https://medium.com/@antonioval/making-array-iteration-easy-when-using-async-await-6315c3225838
Using async/await with a forEach loop
I have to use promise to make sure all callback iteratees have finished. So using bluebird promise.map helps to reduce boilerplate codes
return
nothing from the arrow func, therefore it is undefined, if you return the promise you could usePromise.all
on the returned array. – Jonas Wilmsmap
does not ensure that any callbacks have been called, in fact, it doesn't even know about the asynchronous callbacks you passed toreadFile
. It only cares about the return value of themap
callback itself, which isundefined
. Just go and use promises, you still can ignore their results - but you need them to be able to wait for them. – Bergi