作者:许心怡917 | 来源:互联网 | 2024-11-05 19:04
项目中有一个数据是二层嵌套数组,数据类型类似这样12345678910111213141516171819202122questions: [ { type: 'INPUT',
项目中有一个数据是二层嵌套数组,数据类型类似这样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| questions: [
{
type: 'INPUT',
answer: 'helloworld'
},
{
type: 'SELECT',
answer: '1'
},
{
type: 'GROUP',
sub_questions: [
{
type: 'INPUT',
answer: 'hihi'
},
{
type: 'SELECT',
answer: '2'
}
]}
] |
然后我要通过重组数据将这些数据展示出来,但是select显示的值并不是answer,而是将answer传到后端然后拿到的一个结果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| let answer_arr = [];
questions.forEach(async (question) => {
let single_answer = {type: question.type};
if (question.type === 'INPUT') {
single_answer.answer = question.answer;
} else if (question.type === 'SELECT') {
await axios.post('xxxx', {code: question.code}).then(res => {single_answer.answer = res.data.data})
} else if (question.type === 'GROUP') {
single_answer.answer = [];
question.sub_questions.forEach(async (sub_question) => {
let single_sub_answer = {type: sub_question.type};
if (sub_question.type === 'INPUT') {
single_sub_answer.answer = question.answer;
} else if (sub_question.type === 'SELECT') {
await axios.post('xxxx', {code: sub_question.code}).then(res => {single_sub_answer.answer = res.data.data})
single_answer.answer.push(single_sub_answer )
})
}
answer_arr.push(single_answer)
}) |
期望得到的结果就是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| answer_arr = [
{
type: 'INPUT',
answer: 'helloworld'
},
{
type: 'SELECT',
answer: 1对应的值
},
{
type: 'GROUP',
answer: [
{
type: 'INPUT',
answer: 'hihi'
},
{
type: 'SELECT',
answer: 2对应的值
},
]
}
] |
但是执行后发现await并没有生效,answer_arr 中 type为SELECT时,并没有answer。。。
是不是async/await用法不对。。。