gpt4 book ai didi

javascript - 我可以在不使用计数变量的情况下解决 asyncMap 吗?

转载 作者:行者123 更新时间:2023-11-30 19:22:34 26 4
gpt4 key购买 nike

有没有一种方法可以在不使用计数器变量的情况下编写下面的函数来知道超时何时完成。

可以使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com