postman - Postman:如何通过脚本发送异步请求
问题描述
我收到了两个请求:邮递员中的 A 和 B。我想先发送请求 A,然后在请求 A 仍在等待响应时发送请求 B。手动执行此操作非常容易,因为请求 A 需要 15 秒才能完成。
但是无论如何我可以自动执行此操作,因为我将对此案例进行很多测试。
我曾尝试在邮递员中使用跑步者,但它总是在发送请求 B 之前等待请求 A 完成。
之后我在这里找到了一篇关于在邮递员中发送异步请求的文档。
我编写了一个pm.sendRequest
用于发送请求 B 的脚本,并将该脚本放在请求 A的预请求中。
let confirmRequest = {
url: url + "/confirm",
method: "POST",
body: {
"requestId": (new Date()).getTime(),
"statusCode": "0",
}
}
setTimeout(function() {
pm.sendRequest(confirmRequest, function (err, res) {
console.log(err ? err : res.json());
});
}, 1500);
问题是即使我已经将它包装在一个setTimeout
函数中,请求 A 仍然等待预请求首先完成。所以最终请求 B 在请求 A 之前发送。
这个问题有什么解决办法吗?
解决方案
I tried but could not achieve asynchronously process requests using Postman or Newman. I found it easier to write a nodeJS code using async-await-promise concepts. Here is the sample code:
对我有用的示例代码:
var httpRequest "your raw request body";
var headersOpt = {
"content-type": "application/json",
};
const promisifiedRequest = function(options) {
return new Promise((resolve,reject) => {
request(options, (error, response, body) => {
if (response) {
return resolve(response);
}
if (error) {
return reject(error);
}
});
});
};
var output;
async function MyRequest(httpRequest,j, fileName) {
var options = {
uri: "url",
method: "POST",
body: httpRequest,
json: true,
time: true,
headers: headersOpt
}
try {
console.log('request posted!');
let response = await promisifiedRequest(options);
console.log('response recieved!');
output = output + ',' +response.elapsedTime;
console.log(response.elapsedTime);
console.log(output);
//return response;
} catch (err) {
console.log(err);
}
finally
{
//this code is optional and it used to save the response time for each request.
try{
fileName = (j+1)+'_'+fileName;
fs.writeFile('/logs-async/scripts/output/'+fileName+'.csv', output, (err) => {
//throws an error, you could also catch it here
if (err) throw err;
});
}
catch (err){
console.log(err);
}
}
}
推荐阅读
- c++ - 浮点类型表示
- python - SyntaxError: 无效的语法没有解决方案
- android - 如何让cordova、Java SDK和Android SDK协同工作?
- swift - 在 xcode 命令行应用程序中读取文件时遇到问题
- java - 如何可视化 Stream 对象(和其他一些数据类型)?
- function - 如何在颤振中制作循环函数
- c++ - 试图理解为什么我的链表只显示最后添加的节点
- c++ - 这些带有 char 数组的新表达式中,哪些格式正确?
- flutter - protoc-gen-dart:插件失败,状态码为 127
- python - 403 权限缺失或不足 python firestore-client