You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

  1. Variable Typo & Initialization: You declared createdISCompleted (uppercase 'S') but tried to use createdIsCompleted (lowercase 's') later. Plus, it's uninitialized, so the first loop check will treat it as undefined (which evaluates to false), meaning your loop might not run at all.
  2. Inverted Loop Condition: Your goal is to keep looping until the second request returns createdIsCompleted: false—so you need to loop while the value is true, not false.
  3. 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.post blocks execution until it receives a response, so the second request will always run after the first one completes—no await needed.
  • Correct Loop Logic: We initialize createdIsCompleted to true to ensure the first loop runs, and keep looping as long as the value stays true.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:48:15