简体   繁体   中英

Async / Await not actually waiting in while loop

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

You have to put while loop inside async and use await for statements in order to execute them synchronously.

you can wrap while inside async as shown below and omit unnecessary sendOff() method. Also you should pass final_tweet as a paramter.

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); 
}
})()
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 function sendOff(final_tweet ) {
  await sendTweets(final_tweet );
}


(async () => {
while (1) {

  var final_tweet = {  // Create tweet struct
    status: "Hi!"
  }

  await sendOff(final_tweet);

  sleep.sleep(4);
})()

As you've probably noticed, you can't use await outside the function scope.

If you were to place the while loop inside an asynchronous function, in which you can await sendOff , it should work.

(async () => {
    while (true) {
        var final_tweet = {  // Create tweet struct
            status: "Hi!"
        }

        await sendOff();
    }
})();

Using JavaScript's Arrow Functions to avoid declaring a new function.

You would also have to declare final_tweet globally, as it's not defined inside sendTweets . Either that, or make it a function parameter. (@Nitin Goyal did exactly this in his answer)

So:

var final_tweet;

function sendTweets() { 
    ...
}

...

(async () => {
    while (true) {
        // notice the missing 'var'; we're assigning the new Object to the global final_tweet
        final_tweet = {  // Create tweet struct
            status: "Hi!"
        }

        await sendOff();
    }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM