如何在循环数组中给 axios 延迟?

Seh*_*ark 1 javascript synchronization node.js vue.js axios

我试图在循环数组(Vue 项目)中给 axios 延迟。

        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)
         }
Run Code Online (Sandbox Code Playgroud)

我如何每 3 秒调用一次 axios 函数?

Seh*_*ark 5

我用以下代码解决了我的问题。这个对我有用。

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()
Run Code Online (Sandbox Code Playgroud)