鍍金池/ 問答/HTML/ javascript async/await 使用中遇到的問題

javascript async/await 使用中遇到的問題

項目中有一個數(shù)據(jù)是二層嵌套數(shù)組,數(shù)據(jù)類型類似這樣

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

然后我要通過重組數(shù)據(jù)將這些數(shù)據(jù)展示出來,但是select顯示的值并不是answer,而是將answer傳到后端然后拿到的一個結(jié)果。

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

期望得到的結(jié)果就是

answer_arr = [
    {
        type: 'INPUT',
        answer: 'helloworld'
    },
    { 
        type: 'SELECT',
        answer: 1對應的值
    },
    {
        type: 'GROUP',
        answer: [
            {
                type: 'INPUT',
                answer: 'hihi'
            },
            { 
                type: 'SELECT',
                answer: 2對應的值
            },
        ]
    }
]

但是執(zhí)行后發(fā)現(xiàn)await并沒有生效,answer_arr 中 type為SELECT時,并沒有answer。。。
是不是async/await用法不對。。。

回答
編輯回答
遲月

這句話await一下

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

不過await后面要包裝成promise
async只能保證這個函數(shù)內(nèi)是同步不能保證這個函數(shù)是同步
建議還是用for循環(huán)沒那么多麻煩

2017年4月30日 01:10