• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 50
  • Last Modified:

JavaScript Async/Await

I'm trying to understand JavaScript async/await. How can I rewrite the below such that the output is "Hi" then "Bye" instead of "Bye" then "Hi":

JSFiddle

sayHi() 
  .then(sayBye);

async function sayHi() {
  await setTimeout(function() {
    $("#myOutput").text('hi');
  }, 1000);
}

async function sayBye() {
  $("#myOutput").text('bye');
}

Open in new window

0
Michael Vasilevsky
Asked:
Michael Vasilevsky
1 Solution
 
leakim971PluritechnicianCommented:
The main issue is you must "resolve" or "reject"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

sayHi().then(sayBye);

async function sayHi() {
  await new Promise(resolve => { // check the expression in the documentation : A Promise or any value to wait for.
	  setTimeout(function() {
	  $("#myOutput").text('hi');
	   resolve();
	  }, 1000);
  });
}

async function sayBye() {
    $("#myOutput").text('bye');
}

Open in new window

0
 
Michael VasilevskySolutions ArchitectAuthor Commented:
Full solution:

(async () => {
  await sayHi() 
  sayBye()
})()

function sayHi() {
  return new Promise(function (resolve) {
    $("#myOutput").text('hi');
      setTimeout(function() {
      resolve()
    }, 1000)
  });
}

function sayBye() {
  $("#myOutput").text('bye');
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now