如何从其他嵌套函数中的回调函数中访问变量?

时间:2018-03-17 00:25:48

标签: javascript callback

帮助我理解一些事情。我有嵌套函数,我需要从最低(最深)到最高(第一个函数 - func1)获取数据。正如@spectras所建议的,我确实尝试使用promises而不是回调无效。

var array = [1,2,3,4,5,6,7,8,9,10];

for (var i = 0; i < array.length; i++){
    if (array[i] == '3'){
        function tfunc1(){
            function tfunc2(){
                function tfunc4(){
                    return new Promise(function(resolve, reject){
                        setTimeout(function(){ // lets suppose that there is some async work here
                            var tsomeData = 'TsomeData';
                            resolve(tsomeData);
                            reject(console.log('tfunc4 ERROR'));
                        }, 2000);
                        console.log('TsomeData callback will be executed after 2 sec');
                    });
                }
            }
            tfunc2();
            function tfunc3(){}
            tfunc3();
        };
        tfunc1();
    }

    if (array[i] == '6'){
        function afunc1(){
            function afunc2(){
                function afunc4(){
                    return new Promise(function(resolve, reject){
                        setTimeout(function(){ // lets suppose that there is some async work here
                            var asomeData = 'AsomeData';
                            resolve(asomeData);
                            reject(console.log('afunc4 ERROR'));
                        }, 2000);
                        console.log('AsomeData callback will be executed after 2 sec');
                    });
                }
                afunc4();
            }
            afunc2();
            function afunc3(){}
            afunc3();
        };
        tfunc1();
    }

    // I need to work with tsomeData here - how to pass it here?
    // I need to work with asomeData here - how to pass it here?

    // some tsomeData + asomeData manimupulation:

    function after(){
        return new Promise(function(resolve, reject){
            setTimeout(function(){ // lets suppose that there is some async work here
                var newData = tsomeData + asomeData;
                resolve(console.log(newData));
                reject(console.log('after ERROR'));
            }, 2000);
            console.log('AsomeData callback will be executed after 2 sec');
        });
    }

    tfunc4().then(function(tsomeData)
    {
        return afunc4(tsomeData);
    }).then(function()
    {
            return after();
    }).catch(function()
    {
        console.log(err);
    });
}

如何在节点中执行此操作?

编辑:代码更新。而更多的细节原因主要是代码..

0 个答案:

没有答案