本帖最后由 locbytes 于 2018-8-28 01:27 编辑
局部去异步是调用了一个叫deasync的包,该包的具体信息可以去npm官方介绍里查看[https://www.npmjs.com/package/deasync]
去异步主要是为了更方便的实现一些比较刁钻的业务逻辑。
[JavaScript] 纯文本查看 复制代码 const deasync = require('deasync');
const request = require('request');
let a = getRes(json);
function(a);
function getRes(jsonData) {
let res, isReturn = false;
request.post({
url: url,
form: {
raw: jsonData
}
},
function(err,httpResponse,body){
if(httpResponse.statusCode===200){
isReturn = true;
}
res=body;
}
);
while(!isReturn){
deasync.runLoopOnce();
}
return res;
}
例如使用anyproxy做某些业务的时候,去异步就能解决自定义规则中异步函数未执行完成就已经返回response的问题,代码参考如下:
[JavaScript] 纯文本查看 复制代码
const AnyProxy = require("anyproxy");
const deasync = require("deasync");
const request = require("request");
const options = {
port: 8080,
rule: {
summary: "xxxxx",
*beforeSendResponse(requestDetail, responseDetail) {
let response = Object.assign({}, responseDetail.response);
response.body = editResponseBody(rawBody);
return {
response: response
};
},
*beforeDealHttpsRequest(requestDetail) {
if(requestDetail.host.indexOf("xxxx")>=0){
return true;
}
},
},
webInterface: {
enable: true,
webPort: 8081
},
throttle: 10240,
forceProxyHttps: false,
wsIntercept: false,
silent: true
};
const proxyServer = new AnyProxy.ProxyServer(options);
proxyServer.start();
console.log("Start, port on "+options.port);
proxyServer.close();
// 因为需求原因将数据通过post请求交给PHP进行处理
function editResponseBody(rawBody) {
let newBody, isReturn = false;
request.post({
url: "xxxx",
form: {
raw: rawBody
}
},
function(err,httpResponse,body){
if(httpResponse.statusCode===200){
isReturn = true;
}
newBody=body;
}
);
while(!isReturn){
deasync.runLoopOnce();
}
return newBody;
}
首先自定义规则内部无法使用async/await,其次写回调的话会出现未回调但是已经返回response的问题。 |