js异步问题处理

问题: axios已经取到值了,为什么打印的res 是空数组呢?
代码如下:

`

async function testDemo(){
    let newNodes = [],
       childNode = [{'name':'1',id:'1'},{'name':'11',id:'11'},{'name':'12',id:'12'}];
    let childProm = childNode.forEach((child)=>{
         return axios.post('/user', {
                        id: child.id
                 })
                 .then(function (result) {
                        newNodes = newNodes.concat(result.values);
                   })
                })
     await Promise.all([childProm])
     return newNodes;
  }
                        
    testDemo().then(res => {
        console.log('res', res)

    })

`

阅读 2.3k
2 个回答

1、Promise.all(e)里的参数需为迭代对象
2、arr.forEach(callback(currentValue [, index [, array]])[, thisArg])的值/返回值为undefined

解决方案:使用Map方法


async function testDemo() {
    let newNodes = [],
        childNode = [{'name': '1', id: '1'}, {'name': '11', id: '11'}, {'name': '12', id: '12'}];

    let a = childNode.map(child =>
            axios.post('/user', {
                id: child.id
            }).then(result => {
                newNodes = newNodes.concat(result.values);
            }));
    await Promise.all(a)
    return newNodes;
}

testDemo().then(res => {
    console.log('res', res)

})

`

async function testDemo(){ 
    let newNodes = [], 
    childNode = [{'name':'1',id:'1'},{'name':'11',id:'11'},{'name':'12',id:'12'}]; 
    let childProm = childNode.map((child)=>{ 
    return new Promise(resolve => { 
        axios.post('/user', { 
            id: child.id 
        }) 
        .then(function (result) {                    
             newNodes = newNodes.concat(result.values); 
             resolve(newNodes)) 
            }) 
           })
         }) 

         await Promise.all(childProm) 
         return newNodes; 
     } 
 
 testDemo().then(res => { console.log('res', res) })

`

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