您可以将SynJS用于此类任务,以下是工作代码:
var SynJS = require('synjs');
var request = require('request');
function requestWrapper(context, url, method, postData) {
console.log('get started:', url, method, postData);
var result = { done: false };
request({
uri: url,
method: method,
postData: postData,
}, function(error, response, body){
result.done = true;
result.body = body;
result.response = response;
console.log('get finished:', url, method, postData);
SynJS.resume(context); // <-indicates that long running functoin is done
});
return result;
}
// synchronous function
function myApiSubmitter(modules) {
var postRes = modules.requestWrapper(_synjsContext, "https://www.google.com/search","POST","asdasd");
SynJS.wait(postRes.done); // <- waits for SynJS.resume, and checks for postRes.done, continues if postRes.done is true
for(var i=0; i<5; i++) {
SynJS.wait(500); // <- waits for 500ms
var getRes = modules.requestWrapper(_synjsContext, "https://www.google.com/","GET",i);
SynJS.wait(getRes.done); // <- waits for SynJS.resume, and checks for getRes.done, continues if getRes.done is true
if(getRes.body.indexOf('some_success_message')>=0) // <- some arbitrary condition to break the cycle
break;
}
};
var modules = {
SynJS: SynJS,
requestWrapper: requestWrapper,
};
SynJS.run(myApiSubmitter,null,modules,function () {
console.log('done');
});
它将产生以下输出:
get started: https://www.google.com/search POST asdasd
get finished: https://www.google.com/search POST asdasd
get started: https://www.google.com/ GET 0
get finished: https://www.google.com/ GET 0
get started: https://www.google.com/ GET 1
get finished: https://www.google.com/ GET 1
get started: https://www.google.com/ GET 2
get finished: https://www.google.com/ GET 2
get started: https://www.google.com/ GET 3
get finished: https://www.google.com/ GET 3
get started: https://www.google.com/ GET 4
get finished: https://www.google.com/ GET 4
done