Как перебирать вызовы API - PullRequest
       5

Как перебирать вызовы API

0 голосов
/ 07 декабря 2018

Я пытаюсь перебрать координаты конечной точки 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)
  })

Эта реализация обещаний отправляет все запросы одновременно.Им нужна задержка между ними.В идеале, когда первый запрос получает ответ, второй отправляется.

1 Ответ

0 голосов
/ 07 декабря 2018

Мне нравится использовать небольшую вспомогательную функцию под названием 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...