我遇到了循环一些数据的情况,我需要对每个数组元素执行异步操作。我不想在循环内等待结果。相反,我只想从循环开始执行promises。循环完成后,我要等到所有promise都解决后再返回一些结果。
代码如下:
size_t limit = 1024u; // For example!
char* str = malloc(limit);
int count = 0;
while ((c = getchar()) != EOF) {
str[count] = c;
if (++count >= limit) {
limit += 1024u;
char *str2 = realloc(str, limit); // Shouldn't use same pointer ...
if (!str2) { // ... failure!
// <Some error message/flag>
break;
}
else str = str2; // Successful realloc
}
}
我想我可以创建另一个诺言const t1 = delay => new Promise(resolve => {
setTimeout(() => {
console.log('from t1')
resolve()
}, delay)
})
const promises = []
const results = []
const array = [1 ,2]
array.forEach((element, index) => {
const temp = t1((index + 1) * 1000).then(() => results.push(5))
promises.push(temp)
})
const mainFunc = async () => {
const bigPromise = () => new Promise(resolve => {
if (results.length === 2) {
resolve()
}
})
await bigPromise()
console.log(results)
}
mainFunc()
,该诺言将检查数组长度是否为bigPromise
。这样,我将知道所有的诺言都实现了。但是,这不起作用。如何等待Java中的某些通知?我不想使用2
解决这个问题。