asyncRequest( method, url, [body], [params] )
参数 | 类型 | 描述 |
---|---|---|
method | string | 请求方法(例如 'POST' )。必须为大写。 |
url | string / HTTP URL | 请求 URL(例如 'http://example.com' )。 |
body (可选) | string / object / ArrayBuffer | 请求体。对象将进行 x-www-form-urlencoded 编码。 |
params (可选) | object | 包含附加请求参数的Params 对象。 |
返回值
类型 | 描述 |
---|---|
Promise with Response | HTTP Response 对象。 |
示例
使用 http.asyncRequest() 发起 POST 请求
import http from 'k6/http';
const url = 'https://quickpizza.grafana.com/api/post';
export default async function () {
const data = { name: 'Bert' };
// Using a JSON string as body
const res = await http.asyncRequest('POST', url, JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
console.log(res.json().name); // Bert
// Using an object as body, the headers will automatically include
// 'Content-Type: application/x-www-form-urlencoded'.
await http.asyncRequest('POST', url, data);
}
使用 http.asyncRequest()
发起多个请求,然后使用 Promise.race 确定哪些请求先完成
import http from 'k6/http';
export default async () => {
const urlOne = `https://quickpizza.grafana.com/api/delay/${randomInt(1, 5)}`;
const urlTwo = `https://quickpizza.grafana.com/api/delay/${randomInt(1, 5)}`;
const urlThree = `https://quickpizza.grafana.com/api/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);
}
注意
http.asyncRequest
目前无法中止请求。在上面的脚本中,在
res
获取最快请求的值后,其他请求将继续执行。这可能会阻塞迭代的结束,因为迭代只有在所有异步作业完成后才会停止。