JS Get调用相互等待
JS Get Calls wait Each other
我有一个函数发送GET http请求与请求包。
//file1.js
var request = require('request');
methods.testcall = function(callback){
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
callback(body)
}
if(!error && response.statusCode == 429){ // Rate limit.., try again 1s
setTimeout(this(callback), 1000);
}
})
};
在下一个文件中,我调用了这个函数两次。我想这两个请求可以同时运行。所以当请求到达时,我调用回调函数。在日志中我看到了结果。但是,在你看到我的评论,我想等待所有testcall(),因为我想确保在所有的数据到达我的服务器。
//file2.js
test.methods.testcall(function(response){
console.log(response)
});
test.methods.testcall(function(response){
console.log(response)
});
// Here, i want to wait for all testcall function.
// When all testcall function sent response
// Im ready to do smtng :)
我如何在那里等待这两个方法?非常感谢!
这个没有经过测试,我认为它会为你工作,它使用的是q
var request = require('request');
var Q = require('q');
methods.testcall = function (url) {
return request(url, function (error, response, body) {
//
});
};
Q.allSettled([
method.testcall('http://'),
method.testcall('http://')
]).done(function (results) {
results.forEach(function (result) {
//
});
});
可以嵌套testcall调用:
test.methods.testcall(function(response1) {
test.methods.testcall(function(response2) {
doSomething(response1, response2)
})
})
对testcall
内部调用的回调将在该请求完成之前执行,从而使您可以访问两个响应。
这种方法可能很难遵循,特别是如果您有更多的调用。你必须继续嵌套它们(也称为回调地狱)
为了简化这个过程,你还可以使用async.js这样的库,或者使用Bluebird.js这样的Promise库
对于并发请求,请查看以下问题的详细方法:我如何等待一组异步回调函数?现在它的工作,好
methods.test = function (callback){
request(url...., function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("done");
callback(body)
}else if(!error && response.statusCode == 429){ // Rate limit
console.log("rateLimit");
setTimeout(function(){
methods.test(callback)
},1000);
}else if(!error && response.statusCode == 403){ // Forbidden
console.log("Forbidden");
setTimeout(function(){
methods.test(callback)
},1000);
}
})
};
var responseNumber = 0;
test.methods.test(function(response){
responseNumber += 1;
checkResponse(responseNumber)
});
test.methods.test(function(response){
responseNumber += 1;
checkResponse(responseNumber)
});
function checkResponse(responseNumb)
{
if(responseNumb == 2){
console.log("done");
}
}
相关文章:
- 等待循环调用的所有承诺完成
- 如何使用jQuery等待来自回调的异步调用
- 正在等待HTTP调用从函数返回结果
- Ajax jQuery同时进行多个调用-等待应答的时间很长,无法取消
- 如何在for循环中等待一个,直到ajax调用完成
- jQuery验证,在继续之前等待服务调用响应
- Javascript异步/等待ajax调用
- 等待异步结果的 Chrome 系统调用
- 等待另一个 js 文件中的 ajax 调用
- 如何对页面进行 ajax 调用并等待该页面上的 ajax 调用完成
- 如何等待所有 XHR2 发送调用完成
- 等待多个 ipc 调用完成,然后再继续电子/冗余
- 为什么当我调用 Meteor.setTimeout() 时,我后续的 Meteor 方法调用不会等待第一个方法完成
- 等待 busboy on #file 完成,然后再调用 on#finish
- 等待 API 调用在 Javascript 中完成,然后再继续
- 请等待异步操作 (firebase) 调用完成,然后再加载网页
- 并行调用异步/等待函数
- Angular2 可观察 - 等待多个函数调用,然后再继续
- 在继续Javascript之前,如何等待多个facebook图形api调用
- 等待调用函数完成,然后再向前迭代