gpt4 book ai didi

javascript - array.push 没有根据序列推送对象,而某些对象使用等待执行操作

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:20 26 4
gpt4 key购买 nike

我正在尝试使用map循环我的对象,在map内部我需要使用sequelize执行操作,因此我使用asyncPromise.all来支持async,但它给我的结果是对象序列与原始序列不同,该序列以不使用sequelize执行操作的数据开始。

例如:

const data = await Student.findAll({
limit: 2,
where: {
level: 'Primary 1'
},
order: [['id', 'ASC']]
}).then(async resultStudent => {
// [{"id": 1, "name": "Alex", "gender": "Male", "level": "Primary 1"}, {"id": 2, "name": "Betty", "gender": "Female", "level": "Primary 1"}]

let finalData = [];

await Promise.all(
resultStudent.map(async (e, index) => {

let studentHobbies;
if(e.gender == 'Male'){
studentHobbies = await Hobbies.findOne({
where: {
studentID: e.id
}
})
}

let obj = {
id: e.id,
hobby: studentHobbies ? studentHobbies.hobbyName : null
};

finalData.push(obj);
})
)
})

上面的代码给出的结果为:

[{
"id": 2,
"hobby": null
}, {
"id": 1,
"hobby": "Playing Guitar, and Basketball"
}]

虽然我的预期结果是:

[{
"id": 1,
"hobby": "Playing Guitar, and Basketball"
}, {
"id": 2,
"hobby": null
}]

最佳答案

尝试使用带有异步回调的 map 来保持顺序:

const data = await Student.findAll({
limit: 2,
where: {
level: 'Primary 1'
},
order: [['id', 'ASC']]
}).then(resultStudent => Promise.all(
resultStudent.map(async student => ({
id: student.id,
hobby: (student.gender === 'Male')
? await Hobbies.findOne({ where: { studentID: student.id } })
: null
})
)))

编辑:更易于阅读的版本

const data = await Student.findAll({ // array of ordered results from query
limit: 2,
where: {
level: 'Primary 1'
},
order: [['id', 'ASC']]
}).then(results =>
results.map(async ({ id, gender }) => ({ // array of promises that run asynchronously and resolve with formatted objects
id,
hobby: (gender === 'Male')
? await Hobbies.findOne({ where: { studentID: id } })
: null
}))
).then(Promise.all) // array of results of resolved promises, in same order. resolves when all have completed

这三个数组中的每一个都包含在一个 promise 中。 const data = wait 从 Promise 链的末尾提取最终结果。

关于javascript - array.push 没有根据序列推送对象,而某些对象使用等待执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59221505/

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