gpt4 book ai didi

javascript - 如何等待 forEach 循环中的所有 Promise 添加到数组中?

转载 作者:行者123 更新时间:2023-11-28 17:42:09 25 4
gpt4 key购买 nike

我希望我的函数返回 promise 数组。函数内的代码是异步的。我需要检查每个元素的类型并进行一些处理。我不知道该函数如何在完成异步处理后返回所有 promise 。 JSFiddle

function addFeatures (input) {

var result = [];
input.forEach(function (el) {

if (Number.isInteger(el)) {
// placeholder asynchronous
setTimeout(function () {
result.push(
new Promise(function (resolve, reject) {
resolve(el.toString() + 'string')
})
)
}, 2000);
}
else {
// placeholder synchronous
result.push(
new Promise(function (resolve, reject) {
resolve(el + 'string')
}));
}
})
return result;
};

var arr = [1, 'text']
var final = addFeatures(arr)
// should log 2 promises but logs only 1 - the synchronous
console.log(final)

最佳答案

重要的是立即创建 Promise 并在其中执行异步操作:

function addFeatures (input) {
var result = [];
input.forEach(function (el) {
result.push(new Promise(function (resolve, reject) {
if (Number.isInteger(el)) {
// placeholder asynchronous
setTimeout(function () {
resolve(el.toString() + 'string')
}, 2000);
} else {
// placeholder synchronous
resolve(el + 'string')
}
});
});
return result;
}

我还建议使用 map 而不是 forEach+push

关于javascript - 如何等待 forEach 循环中的所有 Promise 添加到数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47683794/

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