我试图遍历API端点的坐标并测试每个响应。当我不将请求嵌套在for循环中时发送请求时,它可以正常工作,但是,嵌套时似乎不发送请求。
如何使用各种坐标自动测试此端点?
const request = require('request')
const domain = 'host.local'
const port = '8085'
const url = 'http://' + domain + ':' + port + '/v1/vend/item'
const parameters = {
coordinate: {
x: null,
y: null
},
network: {
user: "config",
role: "admin"
}
}
const x_coordinates = [1,2,3,4,5]
const y_coordinates = [6,7,8,9,10]
let options = {
method: 'post',
body: parameters,
json: true,
url: url
}
for (item in x_coordinates) {
parameters.coordinate.x = parseInt(item) + 1
for (item in y_coordinates.length) {
parameters.coordinate.y = parseInt(item) + 7
sleep(10000)
request(options, (err, res, body) => {
var headers = res.headers
var statusCode = res.statusCode
})
}
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break
}
}
}
替代承诺方法
for(let i=0; i<x_coordinates.length; i++) {
body.coordinate.x = i
for(let j=0; j<y_coordinates.length; j++) {
body.coordinate.y = j
let options = {
url: 'http://' + domain + ':' + port + '/v1/vend/item',
method: 'post',
json: true,
body: body
}
ps.push(rp(options))
}
}
Promise.all(ps)
.then((results) => {
console.log(results)
})
.catch(err => {
console.log(err)
})
promise的此实现一次发送了所有请求。他们之间需要延迟。理想情况下,一旦第一个请求得到响应,便发送第二个请求。
答案 0 :(得分:1)
我喜欢使用一个名为chainAsync
的辅助功能:
https://github.com/30-seconds/30-seconds-of-code#chainasync
这里写得不太密集:
function chainAsync(arrayOfFunctions){
let currentFunctionIndex = 0
const lastFunction = arrayOfFunctions[arrayOfFunctions.length - 1]
goToNextFunction()
function goToNextFunction(){
const currentFunction = arrayOfFunctions[currentFunctionIndex]
if(currentFunction == lastFunction){
currentFunction()
}else{
currentFunction(goToNextFunction)
currentFunctionIndex += 1
}
}
}
您可以像这样使用它:
chainAsync([
function(goToNextFunction){
request(options, (err, res, body)=>{
// Handle the response. Then...
goToNextFunction()
})
},
function(goToNextFunction){
request(options, (err, res, body)=>{
// Handle the response. Then...
goToNextFunction()
})
},
function(){
request(options, (err, res, body)=>{
// Handle the response. Then...
// ...don't go to next function, since there isn't a next function!
})
}
])
这样,您可以控制这些异步功能的发生顺序。
这里是使用它来解决用例的一种方法:
const requestsToExecute = []
x_coordinates.forEach(x=>{
y_coordinates.forEach(y=>{
const currentRequest = function(goToNextRequest){
const requestOptions = {
url: 'http://host.local:8085/v1/vend/item',
method: 'POST',
json: true,
body: {
coordinate: {x, y},
network: {
user: 'config',
role: 'admin'
}
}
}
request(requestOptions, (err, response, body)=>{
// Handle the response, then...
// ...if there's another request...
if(goToNextRequest){
// ...use setTimeout to wait 1e7 seconds before going to the next request
setTimeout(goToNextRequest, 1e7)
}
})
}
requestsToExecute.push(currentRequest)
})
})
chainAsync(requestsToExecute)