gpt4 book ai didi

javascript - 如何为 Promise.all 参数映射一个字符串数组?

转载 作者:行者123 更新时间:2023-11-29 20:50:54 25 4
gpt4 key购买 nike

我想要做的是使用一个字符串数组来使用这些值来为 Promise.all 参数映射一个新的 promise 函数数组。

我想解释了我到目前为止的思考过程,以及我遇到的问题。

const strings = ['A', 'B', 'C'] // Varies in size
const stringFunctions = strings.map(item => {
const func = () => {
promised(item) // Returns Promised Boolean
}
return func
})

const PromiseAll = new Promise(function(resolve, reject) {
Promise.all(stringFunctions)
.then(items => {
const obj = {};
items.forEach((item, index) => {
obj[strings[index]] = item;
});
resolve(obj);
// returns { A: func(), B: func(), C: func() }
// expected { A: bool, B: bool, C: bool }
})
.catch(error => {
reject(error);
});
}

最佳答案

这可以在没有任何显式 promise 创建的情况下完成(您在 promised 函数和 Promise.all() 中拥有所需的一切)。

let strings = [ ... ]
let promises = strings.map(string => promised(string));
Promise.all(promises).then(results => {
// results is a new array of results corresponding to the "promised" results
});

关于javascript - 如何为 Promise.all 参数映射一个字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51920988/

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