如何在k6负载测试脚本中等待首个POST请求完成并使用while循环执行两个POST请求直至指定响应条件满足
Fixing k6 Loop for Sequential POST Requests Until Condition is Met
Let's break down what's wrong with your current code and fix it step by step—k6's HTTP methods are actually synchronous (they block execution until the response is received), so you don't need await to sequence your requests. The main issues are with your loop logic and variable handling.
Problems in Your Original Code
- Variable Typo & Initialization: You declared
createdISCompleted(uppercase 'S') but tried to usecreatedIsCompleted(lowercase 's') later. Plus, it's uninitialized, so the first loop check will treat it asundefined(which evaluates tofalse), meaning your loop might not run at all. - Inverted Loop Condition: Your goal is to keep looping until the second request returns
createdIsCompleted: false—so you need to loop while the value istrue, notfalse. - Unnecessary
break: That line immediately terminates the loop after one iteration, so you never get to repeat the requests.
Corrected Code
Here's the fixed version that meets your requirements:
import http from 'k6/http'; import { sleep } from 'k6'; // Assume these variables are defined elsewhere in your script let createdCellLabel = "your-cell-label"; let createdpickingProcessReferenceNumber = "your-ref-number"; let createdAllocatedItemId = "your-item-id"; let createdPickingToteLabel = "your-tote-label"; let createdProductLabel = "your-product-label"; let requestUrlAPI = "https://your-api-endpoint.com/"; let generateTokenHeader = { headers: { 'Authorization': 'Bearer your-auth-token', 'Content-Type': 'application/json' } }; export default function () { // Initialize to true so the first iteration runs let createdIsCompleted = true; // Loop as long as isCompleted is true while (createdIsCompleted) { // First POST: waits for response before moving on (k6 HTTP is synchronous) const checkCellResponse = http.post( `${requestUrlAPI}PickingProcess.checkCell`, JSON.stringify({ cellLabel: createdCellLabel, pickingReferenceNumber: createdpickingProcessReferenceNumber, allocatedItemId: createdAllocatedItemId, }), generateTokenHeader ); // Optional: handle failed first request if (checkCellResponse.status !== 200) { console.error(`Check Cell request failed with status: ${checkCellResponse.status}`); break; // Exit loop if critical failure } // Second POST: runs only after first request completes const placeProductResponse = http.post( `${requestUrlAPI}PickingProcess.placeProduct`, JSON.stringify({ cellLabel: createdCellLabel, pickingReferenceNumber: createdpickingProcessReferenceNumber, pickingToteLabel: createdPickingToteLabel, productLabel: createdProductLabel, allocatedItemId: createdAllocatedItemId, }), generateTokenHeader ); // Optional: handle failed second request if (placeProductResponse.status !== 200) { console.error(`Place Product request failed with status: ${placeProductResponse.status}`); break; } // Update loop condition with the latest response value createdIsCompleted = placeProductResponse.json().isCompleted; // Optional: Add a small delay to avoid overwhelming your API sleep(1); } console.log("Loop finished - isCompleted is now false"); }
Key Fixes & Explanations
- Synchronous Request Handling: k6's
http.postblocks execution until it receives a response, so the second request will always run after the first one completes—noawaitneeded. - Correct Loop Logic: We initialize
createdIsCompletedtotrueto ensure the first loop runs, and keep looping as long as the value staystrue. - Error Handling: Added checks for HTTP 200 status to avoid infinite loops if the API starts failing.
- Consistent Variable Names: Fixed the typo to ensure the loop condition updates correctly.
- Rate Limiting: The optional
sleep(1)adds a 1-second delay between iterations to prevent hitting API rate limits.
内容的提问来源于stack exchange,提问作者Yusuf ÖZTÜRK
相关产品推荐
相关产品推荐

