我需要在 Postman 中重试特定请求,直到任务被解锁。 我不知道要花多长时间,可能是1秒到1分钟。 由于异步行为,下面的脚本似乎并不总是有效。
您在这里推荐什么样的解决方案?
function checkIfTaskIsLocked(responseJson) {
if(responseJson.items && responseJson.items(taskId) {
if (responseJson.items[taskId].isLocked === false {
return true;
} else {
console.log("task is locked");
return false
}
} else {
console.log("task not found")
return false;
}
}
if(!checkIfTaskIsLocked(responseJson)) {
console.log("retrying request")
setTimeout(function() {
pm.execution.setNextRequest(pm.info.requestName)
}, 10000)
}
这应该做:
var maxNumberOfTries = 12; // Retry up to 12 times
var sleepBetweenTries = 5000; // 5 seconds between tries
// Helper function to check if the task is locked
function checkIfTaskIsLocked(responseJson) {
if (responseJson.items && responseJson.items[taskId]) {
if (responseJson.items[taskId].isLocked === false) {
return true;
} else {
console.log("Task is locked");
return false;
}
} else {
console.log("Task not found");
return false;
}
}
// Initialize or increment the retry count
if (!pm.environment.get("collection_tries")) {
pm.environment.set("collection_tries", 1);
} else {
var tries = parseInt(pm.environment.get("collection_tries"), 10);
pm.environment.set("collection_tries", tries + 1);
}
// Check if the task is unlocked or if the maximum number of tries has been reached
if (!checkIfTaskIsLocked(responseJson) && pm.environment.get("collection_tries") < maxNumberOfTries) {
console.log("Retrying request... Attempt: " + pm.environment.get("collection_tries"));
setTimeout(function() {
postman.setNextRequest(pm.info.requestName); // Retry the same request
}, sleepBetweenTries);
} else {
// Reset the retry count after success or reaching the max number of tries
pm.environment.unset("collection_tries");
// You can add tests or other logic here
pm.test("Task unlocked or max retries reached", function() {
pm.expect(checkIfTaskIsLocked(responseJson)).to.be.true;
});
}
它基于一个解决方案,我发明的解决方案仅在我得到好的答案时执行测试:https://community.postman.com/t/retry-a-failing-request/5934