gpt4 book ai didi

javascript - Promise 并不总是从 Web 服务中获取所有值

转载 作者:行者123 更新时间:2023-12-03 00:23:24 25 4
gpt4 key购买 nike

我正在使用我创建的多个 Web 服务来使用 Promise 来填充数组 (this.batGradesProvider.getAllCourseIds() && provider.getCoursesGrades) 但我不这样做始终从我的网络服务中获取所有值。例如,对于我的一个测试用例,我知道我有一系列 6 个类(class)成绩,但最后我只收到 2 个。我的 promise 或 forEach 是否做错了什么?提前致谢。

const promise = this.batGradesProvider.getAllCourseIds();

promise.then((courseIds) => {

courseIds.forEach((courseId) => {

const promise2 = provider.getCoursesGrades(siteId, courseId, userid);
promise2.then((data) => {

for (let i = 0; i < data.data.length; i++) {
// Get this course
const activity = data.data[i];

const activityObj: Activity = {
courseName: activity.courseName,
courseId: courseId,
name: activity.name,
status: activity.status,
complete: activity.complete,
score: activity.grade,
hasPassed: activity.hasPassed,
user: activity.username,
email: activity.useremail,
activityName: activity.activityname,
activityId: activity.activityid
};
// Add course to our running data
this.batGradesTable.push(activityObj);
}

return this.batGradesTable;
});
});
})

最佳答案

您尝试在 forEach 中执行 promise ,但 forEach 函数不知道它应该等待 promise 完成。当您想要执行许多 Promise 时,您可能需要熟悉 Promise.all

尝试这样的事情:

this.batGradesProvider.getAllCourseIds().then((courseIds) => {
return Promise.all(courseIds.map((courseId) => {
return provider.getCoursesGrades(siteId, courseId, userid);
}).then((results) => {
this.batGradesTable = [];

results.forEach((data) => {
for (let i = 0; i < data.data.length; i++) {
const activity = data.data[i];
const activityObj = { /* ... */ };
this.batGradesTable.push(activityObject);
}
});

return this.batGradesTable;
});
});

关于javascript - Promise 并不总是从 Web 服务中获取所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54206934/

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