undefinedfix
Sign in

JS asynchronous problem handling

SpenserWilson1 edited in Thu, 24 Nov 2022

Question: Axios has got the value. Why is the printed res an empty array? The code is as follows:

`

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 Replies
DGrist
commented on Fri, 25 Nov 2022

1、 Promise.all (e) The parameters in should be iteration object 2 arr.forEach The value / return value of (callback (currentvalue [, index [, array]]] [, thisarg]) is undefined.

Solution: using the map method


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)

})
minhthe
commented on Fri, 25 Nov 2022

`

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

`