gpt4 book ai didi

javascript - 在处理递归时,使用 Promises 的 reduce 模式的替代方案是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:08:13 25 4
gpt4 key购买 nike

注意:我不能使用async

我喜欢在需要遍历数组并对其成员执行相同函数并返回 promise 的情况下使用 reduce 模式,如下所示:

function get_count() {
return new Promise(function(resolve, reject) {
resolve(3);
});
}

function recursively_execute(data) {
return new Promise(function(resolve, reject) {
resolve(data);
});
}

function reduce_promise_pattern() {

const get_batch_run_count = get_count();

const batch_process = get_batch_run_count.then((count_value) => {

const run_count = new Array(count_value).fill('batch');

function recursive_function(data) {
console.log('Running batch!');
return recursively_execute(data).then(() => {
return data;
});
}

return run_count.reduce((previous_promise) => {
return previous_promise.then((previous_response) => {
test_data = {
'test': 1
};
return recursive_function(test_data);
})
}, Promise.resolve())
});
return batch_process;
}

这将运行 3 次,因为 run_count 基本上构建了一个包含 3 个项目的数组。虽然它有效,但对我来说这感觉像是一种破解。

当我的列表已经预先定义了独特的项目并且这些项目单独在 reduce 中用作构建的数据时,这种方法有效,例如,如果我有 3 个步骤要完成,这 3 个步骤都是独一无二的,每个步骤的数据都将在该运行中使用……但就我而言?我只是在欺骗系统,让它认为这些是不同的项目。

有什么替代方案?

最佳答案

您达到了 Promise 链的限制,尽管它们可以工作但不可读。这就是为什么引入 async/await 来准确处理这些用例,使用它们你可以停止所有类型的(嵌套)循环,而不必为每个循环保持 promise :

 async function reducePromisePattern() {
for(let i = await getCount(); i >= 0; i--) {
await recursiveFunction({'test': 1 });
}
}

如果你不能使用/转译async,你仍然可以写一些小 helper 来为你做循环,例如:

 function loopAsync(times, fn) {
function task() {
times--;
if(times <= 0) return;
return fn().then(task);
}

return Promise.resolve().then(task);
}

function reducePromisePattern() {
return getCount().then(function(count) {
return asyncLoop(count, function() {
return recursiveFunction({ test: 1 });
});
});
}

关于javascript - 在处理递归时,使用 Promises 的 reduce 模式的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57459186/

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