有没有办法让我的代码在执行下一段代码之前等待几秒钟? (API 每秒请求数限制)

Is there a way to make my code wait a number of seconds before executing the next piece of code? (API Requests Per Second Limit)

setTimeout() 似乎不起作用,我已经阅读了原因并且我明白了。它是异步的,所以它不会延迟代码中的其他函数 运行。那么我怎样才能让它在发送另一个 axios.request 之前等待几秒钟?我问这个的原因是因为 API 即时请求每秒只允许一个请求。

setTimeout(function () {
            axios.request(options).then(function (response) {
                for (let i = 0, l = response.data["result"].length; i < l; i++) {

                    var obj = response.data.result;
                    
                    
                    console.log(response.data.result[i].hash);
                }
                options.params.term = obj[1].hash
                options.params.func = 'dehash'
                setTimeout(function () {
                    axios.request(options).then(function (response2) {
                        
                        message.reply(termargs + " passwords:" + '`' + JSON.stringify(response2.data.found) + '`');
                    });
                }, 1250);
                options.params.term = obj[2].hash
                setTimeout(function () {
                    axios.request(options).then(function (response3) {
                        
                        message.reply(termargs + " passwords:" + '`' + JSON.stringify(response3.data.found) + '`');
                    });
                }, 1250);
                options.params.term = obj[3].hash
                setTimeout(function () {
                    axios.request(options).then(function (response4) {
                        
                        message.reply(termargs + " passwords:" + '`' + JSON.stringify(response4.data.found) + '`');
                    });
                }, 1250); 
               

            }).catch(function (error) {
                message.reply("There was an error!" + '`' + 'Couldnt find user.' + '`');
                console.log(error);
            });
            }, 1250);

我要重申一个事实,我是 Javascript 的新手,这个没有等待功能的东西真的让我的脚趾卷曲,因为我一直在使用另一种名为Lua.

如果你想使用 setTimeout,你应该关注我已经链接到这个线程的线程。

如果对你不起作用,你也可以试试睡眠法

sleep(ms).then(() => {

})

一旦你是 运行 异步函数,你将需要使用 async/await 来做到这一点,setTimeout/Sleep 不会工作。

如果您希望在转到下一个代码时结束请求,您可以这样做:

async function funcName(){
 const result = await axios.request(options).then(function (response2) {
  message.reply(termargs + " passwords:" + '`' + 
  JSON.stringify(response2.data.found) + '`');
 });

 const result2 = await axios.request(options).then(function (response2) {
  message.reply(termargs + " passwords:" + '`' + 
  JSON.stringify(response2.data.found) + '`');
 });
}

funcName();

在这个例子中,他首先会结束结果 1,然后去解决结果 2...

这是文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await