gpt4 book ai didi

javascript - 知道 forEach 循环何时结束

转载 作者:行者123 更新时间:2023-12-03 07:07:54 29 4
gpt4 key购买 nike

我怎么知道我的代码何时完成循环?完成后我还得再运行一些代码,但只有当我在那里写的所有东西都完成后它才能运行。

obj.data.forEach(function(collection) {
var serialized_array = collection['quiz_ids'];
quiz_collections.push([collection['id'], collection['name'], collection['type'], collection['category'], serialized_array.split(',')]);

serialized_array.split(',').forEach(function(ite) {
query('./php/query.php', 2, [['quiz_id', ite]]).then(function(quiz_obj) {
if (quiz_obj.data[0] == 'false') {

}
else {
fetch(quiz_obj.data[0]['data']).then(function(resp) {
return resp.json();
})
.then(function(data) {
console.log(data);
quiz_data.push([quiz_obj['id'], quiz_obj['name'], quiz_obj['version'], quiz_obj['data'], data]);
});
}
});
});
});

如果有帮助。第一行中的 obj.data 如下所示:
the object
这是我的查询函数:

function query(url, cmd_type, data_array) {
var request = new XMLHttpRequest();
var params= '';
params = params + 'cmdtype=' + encodeURIComponent(cmd_type) + '&';
if (data_array) {
data_array.forEach(function(item) {
params = params + item[0] + '=' + encodeURIComponent(item[1]) + '&';
});
}

console.log(params);

return new Promise(function(resolve, reject) {
request.open('POST', url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var response = JSON.parse(request.response);
resolve(response);
}
else {
resolve({error: 'Cant connect!'});
}
}
};
request.send(params);
});
}

提前致谢
菲利普

最佳答案

您可以使用 reduce一个接一个地运行 promise 而不是forEach .

例子:

const data = [1, 2, 3, 4, 5];

const loopResult = data.reduce(async (previous, value) => {
// Wait for previous loop to finish
await previous;

// Return new promise
return new Promise((resolve) => {
// Promise code
// Make HTTP fetch here...
resolve();
});
}, Promise.resolve());

loopResult.then(() => {
console.log('loop finished');
});

或者,如果您的循环不需要有序,您可以使用 Promise.all :

const loopResult = Promise.all(
data.map((value) => new Promise((resolve) => {
// Promise code
// Make HTTP fetch here...
resolve();
}))
);

loopResult.then(() => {
console.log('loop finished');
});

关于javascript - 知道 forEach 循环何时结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64195645/

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