Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

example of promise and async in javascript

// example of promise and async in javascript
// 1) promise: we need to write new keyword to create promise
function withConstructor(num){
  return new Promise((resolve, reject) => {
    if (num === 0){
      resolve('zero');
    } else {
      resolve('not zero');
    }
  });
}

withConstructor(0)
  .then((resolveValue) => {
  console.log(` withConstructor(0) returned a promise which resolved to: ${resolveValue}.`);
});
// Output: withConstructor(0) returned a promise which resolved to: zero.

// 2) async:  we don't need to write new keyword to create promise
async function withAsync(num){
  if (num === 0) {
    return 'zero';
  } else {
    return 'not zero';
  }
}

withAsync(100)
  .then((resolveValue) => {
  console.log(` withAsync(100) returned a promise which resolved to: ${resolveValue}.`);
})

// Output: withAsync(100) returned a promise which resolved to: not zero.
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #promise #async #javascript
ADD COMMENT
Topic
Name
4+5 =