The problem of returning values of variables in callback functions as outer functions

the
code is a multi-layer callback. The example code is as follows

var arr=[];
let A = ()=>{
    //
     B(function(){
            
            C(function(){
                
                 let a = 10;
                 arr.push(a);
            
            })
            
    
    })
    return arr

}

expect the arr in function c as the return value of function A, but because of asynchronism, the return statement will be executed first and undefined

will be returned.
 let data = A();
 

Please do not hesitate to comment


var arr=[];
let A = ()=>{
    //
     return B(function(){
            
            return C(function(){
                
                 let a = 10;
                 arr.push(a);
                 return arr
            })
            
    
    })

}

1. Change asynchronism into synchronous form with await
2. Manually encapsulate the returned logic in then with promise
3. Use callback to pass the returned logic to the inner function through callback


learn about Promise

 let A =new Promise((resolve,reject) => {
    function B(function(){
       resolve();
    })
}).then(()=>{
function C(function(){
                
    let a = 10;
    arr.push(a);
            
  })
})
Menu