[英]Call Back Function in Javascript
I have two functions , Function submitCallbackInfo
is callback function in a loop and XYZ
. 我有两个函数,Function submitCallbackInfo
是循环中的回调函数和XYZ
。 I only want to execute XYZ
once i receive all data from submitCallbackInfo
without using timeout or jQuery. 我只想在收到来自submitCallbackInfo
所有数据后执行XYZ
,而无需使用超时或jQuery。
for (var i = 0; i < 10; i++) {
var id;
myHttp1.connect(url, 'GET', data, submitCallbackInfo);
}
setTimeout(XYZ, 5000);
What i exactly want is to call XYZ
function only when submitCallbackInfo
executes 10 times. 我真正想要的是仅当submitCallbackInfo
执行10次时才调用XYZ
函数。
Check the value of
counter
in thecallback
function 检查callback
函数中counter
的值
var length = 10;
var count = 0;
function submitCallbackInfo() {
if (++count === length) {
createC2VCall();
}
}
for (var i = 0; i < length; i++) {
myHttp1.connect(url, 'GET', data, submitCallbackInfo);
}
Promise
could be used if myHttp1.connect
returns a Promise-object
Promise
如果可以使用myHttp1.connect
返回Promise-object
Alternate to @ Rayon 's answer, you can pass count as parameter. 除了@ Rayon的答案,您可以将count作为参数传递。 You can use .bind()
to do it. 您可以使用.bind()
来做到这一点。
Following is a basic implementation 以下是基本的实现
for (var i = 0; i < 10;) { //myHttp1.connect(url, 'GET', data, submitCallbackInfo.bind(++i)); test(submitCallbackInfo.bind(null, ++i)) } function submitCallbackInfo(count){ var maxCount = 10; console.log('Inside Callback', count) // Do your stuff if(count === maxCount) XYZ(); } function XYZ(){ console.log('Inside XYZ') } function test(callback){ if(callback) callback(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.