JS Get调用相互等待

JS Get Calls wait Each other

本文关键字:等待 调用 Get JS      更新时间:2023-09-26

我有一个函数发送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");
    }
}