javascript async/await 使用中遇到的问题

项目中有一个数据是二层嵌套数组,数据类型类似这样

questions: [
    {
        type: 'INPUT', 
        answer: 'helloworld'
    },
    {
        type: 'SELECT',
        answer: '1'
    },
    {
        type: 'GROUP', 
        sub_questions: [
        {
            type: 'INPUT', 
            answer: 'hihi'
        },
        {
            type: 'SELECT', 
            answer: '2'
        }
    ]}
    ]

然后我要通过重组数据将这些数据展示出来,但是select显示的值并不是answer,而是将answer传到后端然后拿到的一个结果。

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)
})

期望得到的结果就是

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用法不对。。。

阅读 7.2k
1 个回答

这句话await一下

await question.sub_questions.forEach(async (sub_question) => {

不过await后面要包装成promise
async只能保证这个函数内是同步不能保证这个函数是同步
建议还是用for循环没那么多麻烦

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题