Reputation: 143
I'm trying to give a delay to axios in a loop array(Vue project).
let promises = [];
for (const item of this.itemsWithIndex) {
const cmd = "od_kioskPaperUpdate";
promises.push(
await axios({
url: 'url',
method: 'post',
data: data
}).then((res) => {
if (res.statusText == 'OK') {
console.log('success', res)
} else {
console.log("failed", res)
}
})
.catch((err) => {
console.log(err)
})
)}
Promise.all(promises)
.then(async (r) => {
console.log(r)
}
How can I call this each axios function per 3 seconds?
Upvotes: 2
Views: 23149
Reputation: 143
I solved my problem with following code. It works for me.
const axios = require('axios');
let promises = [];
const itemsWithIndex = ['a','b','c','d']
function wait(ms) {
return new Promise( (resolve) => {setTimeout(resolve, ms)});
}
const axiosFunc = async () => {
for (const item of itemsWithIndex) {
console.log('before axios')
axios({
url: 'url',
method: 'post',
data: item
}).then( await wait(5000))
}
};
axiosFunc()
Upvotes: 5
Reputation: 2319
try this it will work for you
let promises = [];
for (const item of this.itemsWithIndex) {
const cmd = "od_kioskPaperUpdate";
promises.push(
await axios({
url: 'url',
method: 'post',
data: data
}).then((res) => {
if (res.statusText == 'OK') {
console.log('success', res)
} else {
console.log("failed", res)
}
})
.catch((err) => {
console.log(err)
})
)
/* You can use Timeout */
setTimeout(() => {
console.log("go_to_sleep")
}, 5000);
}
Promise.all(promises)
.then(async (r) => {
console.log(r)
})
Upvotes: -1
Reputation: 979
Your code is not effective but you can use this where your axios request
setTimeout(() => {
console.log('axios request')
}, 3000)
Upvotes: 2