js promise async await javascript code example

Example 1: nodejs promise async

// server.js
 
function square(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(Math.pow(x, 2));
    }, 2000);
  });
}
 
async function layer(x)
{
  const value = await square(x);
  console.log(value);
}
 
layer(10);

Example 2: javascript async await

// The await operator in JavaScript can only be used from inside an async function.
// If the parameter is a promise, execution of the async function will resume when the promise is resolved
// (unless the promise is rejected, in which case an error will be thrown that can be handled with normal JavaScript exception handling).
// If the parameter is not a promise, the parameter itself will be returned immediately.[13]

// Many libraries provide promise objects that can also be used with await,
// as long as they match the specification for native JavaScript promises.
// However, promises from the jQuery library were not Promises/A+ compatible until jQuery 3.0.[14]

async function createNewDoc() {
  let response = await db.post({}); // post a new doc
  return await db.get(response.id); // find by id
}

async function main() {
  try {
    let doc = await createNewDoc();
    console.log(doc);
  } catch (err) {
    console.log(err);
  }
}
main();