We help IT Professionals succeed at work.

How would I convert this promise to an async / await function?

Bruce Gust
Bruce Gust asked
on
Here's my Promise:

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};

	setTimeout(() => {
	  console.log("Smith and Gone");
	  fetchData()
	  .then(text => {
		console.log(text);
	  });
	}, 200);

});

Open in new window


How would I convert that to an "async / await" dynamic?
Comment
Watch Question

Most Valuable Expert 2017
Distinguished Expert 2019
Commented:
async / await is declared at the function level - you cannot do it at the global level. [for interest]

The syntax is

function async someFunction() {
   var promiseResult = await somePromise;
   // use promiseReulst here
}

Open in new window


In your case we make the arrow function async

setTimeout( async () => {
  console.log("Smith and Gone");
  var text = await fetchData();
  console.log(text);
}, 200);

Open in new window

Bruce GustPHP Developer

Author

Commented:
Julian!

As always, thank you for a thorough explanation!

What you've got works, but I've got one more related question and let me qualify it by saying that at this point, it's not about practical application as much as it's for my own edification.

Could I write "fetchData" as an anonymous function? Not that I would necessarily do that in a practical setting, but I was curious.

You'll find that question at https://www.experts-exchange.com/questions/29172470/Can-This-Code-Work-Using-an-Anonymous-Function.html

As always, thank you for your time, bud!
Bruce GustPHP Developer

Author

Commented:
Smokin'!
Most Valuable Expert 2017
Distinguished Expert 2019

Commented:
You are welcome. (will respond in your other thread)
Bruce GustPHP Developer

Author

Commented:
Rock on!