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



setTimeout((似乎不起作用,我已经读过原因,我理解了。它是异步的,所以它不会延迟代码中的其他函数的运行。那么,我如何才能让它等待几秒钟,然后再发出另一个axios.request呢?我问这个问题的原因是因为API im请求每秒只允许一个请求。

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的编程语言中使用它。

运行异步函数后,您将需要使用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

如果你想使用setTimeout,你应该负责我链接这个线程的线程。

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

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

最新更新