2017-03-08 54 views
1
angular.forEach(tableName, function(value, key){ 
console.log("value ", value) 
getFormsService.getTableData(value).then(function(dynResponse){ 
    console.log("key",key," dynResponse", dynResponse.data) 
      }); 
}); 

在上述代码表名包含表名阵列 例如:表名= [ “表1”, “表2”, “表3”, “tale4”]角的foreach不等待服务器响应

每个表50,10,如图5所示,20个记录

我的输出:

"value ", table1 
    "value ", table2 
    "value ", table3 
    "value ", table4 

    "key",2," dynResponse", array(5 records) 
    "key",1," dynResponse", array(10 records) 
    "key",3," dynResponse", array(20 records) 
    "key",0," dynResponse", array(50 records) 

预期输出:

"value ", table1 
"key",0," dynResponse", array(50 records) 
"value ", table2 
"key",1," dynResponse", array(10 records) 
"value ", table3 
"key",2," dynResponse", array(5 records) 
"value ", table4 
"key",3," dynResponse", array(20 records) 


help me to get expected output 

Thanks 
+0

不要忘了接受答案,如果它帮助你:) –

回答

0
angular.forEach(tableName, function(value, key){ 
    getFormsService.getTableData(value).then(function(dynResponse){ 
     console.log("value ", value) 
     console.log("key",key," dynResponse", dynResponse.data) 
    }); 
}); 

我不确定,你想要做什么。为了同步执行服务请求,您可以使用all()方法$q服务。

0

这里getFormsService.getTableData回调是一个异步调用。因此,循环线程和服务线程不会链接在一起,而是将其他线程链接在一起。

// this line does not wait for service callback to be completed. 
angular.forEach(tableName, function(value, key){ 

    // this is an a asynchronous call 
getFormsService.getTableData(value).then(function(dynResponse){ 
    console.log("key",key," dynResponse", dynResponse.data) 
      }); 
}); 

可以更改服务打一个电话,或使用类似这样

var inUse=false; 
    angular.forEach(tableName, function(value, key){ 

    while (!inUse) { 
     //waiting call might be costly you can try wait here as well 
     } 

    inUse=true; 
     // this is an a asynchronous call 
    getFormsService.getTableData(value).then(function(dynResponse){ 
       console.log("key",key," dynResponse", dynResponse.data) 
       inUse=false; 
       }); 
    }); 
0

JavaScript是始终同步和单线程。由于您正在调用服务代码,所以不会等到获得响应。它会执行代码的其余部分,并在收到响应时执行代码的其余部分。

从它可以进行Ajax调用等方面来说,JavaScript只是异步的。代码将停止执​​行,直到调用返回(成功或以其他方式),此时回调将同步运行。

function FirstFunction(callback) { 
    angular.forEach(tableName, function(value, key){ 
     console.log("value ", value); 
    }); 
    callback(); 
} 

FirstFunction(function() { 
    getFormsService.getTableData(value).then(function(dynResponse){ 
     console.log("key",key," dynResponse", dynResponse.data) 
    }); 
});