Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

js 变量作用域的问题


funcion outFun () {

    let response = [];

    funAAA(a,b,c,function(err,res) {
    
        if(err == 0 ){
            let result = {name:"111",ok:"0"};    
            response.push(result);
        }
        else if(err ==1) {
            let result = {name:"222",tel:"1"};
            response.push(result);
            //response.push({...result});   也不行
            //response.push(JSON.parse(JSON.stringify(result)));也不行
        }
    });

    console.log(response);   // []   空的。。,这

}

这种情况何解?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

image.png
这一坨在回调函数里啊兄弟,是异步的,这一坨没有下面那个console语句跑的块,不行你在那一坨里console试试,看谁先输出。

image.png
处理异步回调方法很多,不过就现在这个情况,
在这个地方加个函数判断下就行了,意思就是每循环一次都判断一下跑完了没,常规做法。比如:
run()
.....

function run(){
    if(response.length  == 遍历的数组的长度){
        //比较有针对性的处理方式
        ....
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...