有没有一种方法可以在不使用计数器变量的情况下编写下面的函数来知道超时何时完成。
可以使用 async/await 来完成吗?
我在下面提供了测试调用和当前工作函数。
// write asyncMap below such that results array holds
// ['one', 'two', 'three']
// when the callback results function is run
// asyncMap has the prototype asyncMap(callbackArray, resultsCallbck)
asyncMap([
(cb) => {
setTimeout(() => {
cb('one');
}, 200);
},
(cb) => {
setTimeout(() => {
cb('two');
}, 300);
},
(cb) => {
setTimeout(() => {
cb('three');
}, 100);
}
],
(results) => {
console.log(results); // ['one', 'two', 'three]
}
);
//
//
function asyncMap(tasks, callback) {
const results = [];
let count = 0;
for (let i = 0; i < tasks.length; i++) {
const func = tasks[i];
// await runFunc();
function cb (val) {
results[i] = val;
count++;
console.log(i, count);
if (count === tasks.length) {
callback(results);
}
}
func(cb);
}
};
最佳答案
这比您想象的要容易得多。
您只需要 Promise.all
.
在不改变你调用asyncMap
的方式的情况下,你可以这样做:
/* Nothing changes here */
asyncMap([
(cb) => {
setTimeout(() => {
cb('one');
}, 200);
},
(cb) => {
setTimeout(() => {
cb('two');
}, 300);
},
(cb) => {
setTimeout(() => {
cb('three');
}, 100);
}
],
(results) => {
console.log(results); // ['one', 'two', 'three]
}
);
/* Reduced the whole function into only 3 lines */
function asyncMap(tasks, callback){
tasks = tasks.map(cb => new Promise(cb))
return Promise.all(tasks)
.then(callback);
}
关于javascript - 我可以在不使用计数变量的情况下解决 asyncMap 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300667/