i want to make a breack of 1 sec into a fetch call and it doesn't work, the code is this:
async function sendStats(image, endimage, chat, id) {
let finalimage = image + endimage;
fetch(finalimage)
.then(res => {
if (res.ok) {
res.body.pipe(fs.createWriteStream('./imgs/image.png'));
bot.sendPhoto(chat, finalimage);
} else {
finalimage = image + "i" + endimage;
fetch(finalimage)
.then(res => {
if (res.ok) {
res.body.pipe(fs.createWriteStream('./imgs/image.png'));
bot.sendPhoto(chat, finalimage);
} else {
bot.sendMessage(chat, "spiacenti ma non abbiamo un immagine di questo mostro :(");
}
})
}
let mstr = mostri.filter(x => x.id == id);
let desc = mstr[0].description;
let elements = mstr[0].elements;
await sleep(1000);
bot.sendMessage(chat, desc);
})
.catch((err) => {
console.log(err)
});
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
i want to send the bot.sendmessage of desc after the sendphoto because is reversed now, and it doesn't give me message errors
The issue with your code is that you are using the await keyword without an async function.
I think you might've gotten confused with this async function when using the await keyword with sleep().
async function sendStats(image, endimage, chat, id) {}
The issue is that your sleep() function is inside another function, so the sendStats() function won't help with its await keyword.
The solution for this issue is to add an async keyword to the function that the sleep() function is in.
fetch(finalImage)
.then(async (res) => {
await sleep(1000);
});
Line 2 has been modified.
The reason this works is because the function in which the await keyword is in has the async keyword added onto the function, which specifies that the function has an asynchronous task in it.
In conclusion, the issue with your code was that you had forgotten to add the async keyword to the function which had await in there.