what is async js code example

Example 1: async await javascript

function hello() {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('I am adam.');
    }, 2000);
  });
}
async function async_msg() {
  try {
    let msg = await hello();
    console.log(msg);
  }
  catch(e) {
    console.log('Error!', e);
  }
}
async_msg(); //output - I am adam.

Example 2: script async syntax

<script src="demo_async.js" async></script>

Example 3: async function someFunction()

async function someFunction() {
	console.log("someFunction");
 }
 
 Console.log("Start");
 someFunction();
 console.log("End");

Example 4: async await js

fetch('coffee.jpg')
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  } else {
    return response.blob();
  }
})
.then(myBlob => {
  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
})
.catch(e => {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});

Example 5: async await javascript

myFunction().then(

  function(value) { /* code if successful */ },

  function(error) { /* code if some error */ }

);

Tags:

Misc Example