Towards then end of my project I realized that for its last component I'd have no choice but to use Async, Await, and Promise in order for the program to wait for an API call to finish and then continue. Although I've learned that there really is no "stopping" or "waiting" in Javascript. I've tried the code below and it works without the while-loop, but with it, it stops working. I want the program to send a tweet API call several times but I feel like the sendOff() function is not actually waiting, and the loop just hops over it because it's going too fast and not waiting for the API call to finish. Any help or a different method of attacking this would be very appreciated.
function sendTweets() {
return new Promise ((resolve, reject) => {
client.post('statuses/update', final_tweet, function(error, tweet, response) {
if (error) {
reject(error);
}
resolve(response);
});
});
}
async function sendOff() {
await sendTweets();
}
while (1) {
var final_tweet = { // Create tweet struct
status: "Hi!"
}
sendOff();
sleep.sleep(4);
}
Edit: For those who ever have the same problem
The following code ended up working out
function sendTweets(final_tweet) {
return new Promise ((resolve, reject) => {
client.post('statuses/update', final_tweet, function(error, tweet, response) {
if (error) {
reject(error);
}
resolve(response);
});
});
}
(async () => {
while (1) {
var final_tweet = { // Create tweet struct
status: "Hi!"
}
await sendTweets(final_tweet);
await sleep.sleep(4);
}
})().catch(e => { console.error(e) }) // Catch needed to prevent "Unhandled Promise Rejection" error
Huge thanks to @knobiDev @TARN4TION @Nitin Goyal