我是nodejs的新手,我想同步执行多个axios请求。可能吗 ?
在下面的示例中,我在data
变量中有3个对象,我想执行第一个请求,只有在收到确认第一个请求已完成的确认后,再执行第二个请求,然后才收到第二个请求的确认请求完成并执行第三个请求,依此类推。我可以在nodejs中做类似的事情吗?还是有更好的方法做到这一点?有人可以帮我显示一些代码示例吗?
谢谢 瓦格纳
const resourceInfo = [
{ resource: "resource1" , route: "http://localhost:3001/api/route1" },
{ resource: "resource2" , route: "http://localhost:3002/api/route2" },
{ resource: "resource3" , route: "http://localhost:3003/api/route3" },
{ resource: "resource4" , route: "http://localhost:3004/api/route4" },
{ resource: "resource5" , route: "http://localhost:3005/api/route5" }
]
function getEndpoint(resource) {
const info = resourceInfo.filter(e => {
if (e.resource === resource) return e.route
})
return info[0]
}
async function doSomeRequests(body) {
const { resourceList } = body
for (element of resourceList) {
const endpoint = getEndpoint(element.resource['route']
const headers = config.get('headers')
const options = {}
options['id'] = element.id
options['val1'] = element.val1
options['val2'] = element.val2
options['val3'] = element.val3
options['val4'] = element.val4
options['val5'] = element.val5
try {
const result = await axios.post(endpoint, options, headers)
io.emit('statusReport', result.data)
} catch (error) {
debug(`Something went wrong: ${error}`)
}
}
}
const data = {
resourceList: [
{id: 355, val1: 1, val2: 2, val3: 3, val4: 4, val5: 5},
{id: 484, val1: 10, val2: 20, val3: 30, val4: 40, val5: 50},
{id: 633, val1: 100, val2: 200, val3: 300, val4: 400, val5: 500}
]
}
await doSomeRequests(data)