Menu

This is documentation for the next version of K6. For the latest stable release, go to the latest version.

Documentationbreadcrumb arrow Grafana k6breadcrumb arrow JavaScript APIbreadcrumb arrow k6/httpbreadcrumb arrow asyncRequest( method, url, [body], [params] )
Open source

asyncRequest( method, url, [body], [params] )

ParameterTypeDescription
methodstringRequest method (e.g. 'POST'). Must be uppercase.
urlstring /HTTP URLRequest URL (e.g. 'http://example.com').
body (optional)string / object / ArrayBufferRequest body. Objects will be x-www-form-urlencoded encoded.
params (optional)objectParams object containing additional request parameters.

Returns

TypeDescription
Promise with ResponseHTTP Response object.

Examples

Using http.asyncRequest() to issue a POST request:

JavaScript
import http from 'k6/http';

const url = 'https://httpbin.test.k6.io/post';

export default async function () {
  const data = { name: 'Bert' };

  // Using a JSON string as body
  let res = await http.asyncRequest('POST', url, JSON.stringify(data), {
    headers: { 'Content-Type': 'application/json' },
  });
  console.log(res.json().json.name); // Bert

  // Using an object as body, the headers will automatically include
  // 'Content-Type: application/x-www-form-urlencoded'.
  res = await http.asyncRequest('POST', url, data);
  console.log(res.json().form.name); // Bert
}

Using http.asyncRequest() to issue multiple requests, then Promise.race to determine which requests finish first:

JavaScript
import http from 'k6/http';

export default async () => {
  const urlOne = `https://httpbin.test.k6.io/delay/${randomInt(1, 5)}`;
  const urlTwo = `https://httpbin.test.k6.io/delay/${randomInt(1, 5)}`;
  const urlThree = `https://httpbin.test.k6.io/delay/${randomInt(1, 5)}`;

  const one = http.asyncRequest('GET', urlOne);
  const two = http.asyncRequest('GET', urlTwo);
  const three = http.asyncRequest('GET', urlThree);

  console.log('Racing:');
  console.log(urlOne);
  console.log(urlTwo);
  console.log(urlThree);

  const res = await Promise.race([one, two, three]);
  console.log('winner is', res.url, 'with duration of', res.timings.duration + 'ms');
};

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

Note

http.asyncRequest has no current way to abort a request.

In the preceding script, after res gets the value from the fastest request, the other requests will continue to execute. This might block the end of the iteration, because the iteration only stops once all async jobs finish.