我需要帮助从头开始编写这个 asyncMap 函数。我想我已经差不多明白了,但我不知道为什么我总是得到错误的答案。这是我到目前为止的代码:
function wait3For1(callback){
setTimeout(function(){
callback('one')
}, 300)
}
function wait2For5(callback){
setTimeout(function(){
callback('five')
}, 200)
}
function asyncMap(tasks, callback){
return callback(
tasks.map((item) =>
item((element) => element)))
}
asyncMap([wait3For1, wait2For5], function(arr){
console.log(arr) //expect ['one', 'five']
});
我不断收到[未定义,未定义]
我很确定这是因为我没有正确执行回调 wait2For5 和 wait3For1,但不确定问题是什么。
提前致谢!
最佳答案
问题是您没有等待结果返回、收集它们,然后通过回调将它们发回。看看这段代码是否有帮助。 (当使用您的程序进行测试时,它可以工作。)
function asyncMap(tasks, callback) {
// array to collect the results
let results = [];
// count of how many results we're waiting for
let remaining = tasks.length;
tasks.forEach((task, i) => {
task((result) => {
// Store the result in the right position.
results[i] = result;
// See how many results we're still waiting for.
remaining -= 1;
// If we're done, invoke the callback.
if (remaining === 0) {
callback(results);
}
});
});
}
关于javascript - 如何从头开始用 Javascript 编写异步 Map 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38386718/