[英]Array.prototype.map() expects a value to be returned at the end of arrow function
[英]Can the next function after Array.prototype.map() safely assume all callback in map have returned?
我知道Array.prototype.map
是一個同步操作。 另一方面,如果map函數是一個回調函數(異步),則undefined
將立即返回。
所以我的問題是,下一個函數可以安全地假定所有回調函數都已完成嗎?
示例代碼可能使我的問題更清楚:
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')
我不在乎返回值。 這就是為什么我不想打擾await/async
。 我只想確保所有回調函數都已調用並返回。 那可能嗎 ?
-------更新--------
除了答案,我發現這些文章還幫助我理解了這個問題: https : //medium.com/@antonioval/making-array-iteration-easy-when-using-async-await-6315c3225838
在forEach循環中使用異步/等待
我必須使用promise來確保所有回調迭代項都已完成。 因此,使用bluebird promise.map有助於減少樣板代碼
您必須使回調函數具有前景,然后可以使用Promise.all:
const results = Promise.all(files.map(file => new Promise(resolve => {
fs.readFile(file, (err, data) => {
if (err) throw err;
resolve(process(file));
});
));
results.then(() => {
console.log('done')
//...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.