Мне нравится использовать небольшую вспомогательную функцию под названием 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)