What's the difference between Async Await and Promise in JavaScript All In One

xgqfrms / 2023-09-01 / 原文

What's the difference between Async Await and Promise in JavaScript All In One

Async vs Promise

demos

async function declaration

// named async function declaration
async function asyncFunctionDeclaration(param0, param1, /* …, */ paramN) {
  // statements
  console.log(`anonymous async function declaration object`)
}


// anonymous async function declaration IIFE
(async function (param0, param1, /* …, */ paramN) {
  // statements
  console.log(`anonymous async function declaration IIFE`)
  return Promise.resolve(`anonymous async function declaration IIFE`)
})().then(msg => {
  console.log(`anonymous msg =`, msg)
  return msg;
})

// named async function declaration IIFE
(async function iife(param0, param1, /* …, */ paramN) {
  // statements
  console.log(`named async function declaration IIFE`)
  return Promise.resolve(`named async function declaration IIFE`)
})().then(msg => {
  console.log(`named msg =`, msg)
  return msg;
})

async function expression

// anonymous async function expression class
class AnonymousAsyncFunctionClass {
  constructor() {
    const add = async function (param0, param1, /* …, */ paramN) {
      // statements
      console.log(`anonymous async function expression class`)
    }
    this.add = add;
  }
  anonym = async function (param0, param1, /* …, */ paramN) {
    // statements
  }
  static test() {
    //
  }
  es5 = function () {
    //
  }
  es6 = () => {
    //
  }
}

// maned async function expression class
class NamedAsyncFunctionClass {
  constructor() {
    const add = async function add(param0, param1, /* …, */ paramN) {
      // statements
      console.log(`named async function expression class`)
    }
    this.add = add;
  }
  named = async function named(param0, param1, /* …, */ paramN) {
    // statements
  }
  static test() {
    //
  }
  es5 = function () {
    //
  }
  es6 = () => {
    //
  }
}


// anonymous async function expression object
const AnonymousAsyncFunctionObject = {
  add: async function (param0, param1, /* …, */ paramN) {
    // statements
    console.log(`anonymous async function expression object`)
  },
}

// named async function expression object
const namedAsyncFunctionObject = {
  add: async function add(param0, param1, /* …, */ paramN) {
    // statements
    console.log(`named async function expression object`)
  },
}


// anonymous async function expression IIFE
const anonymousIIFE = (async function (param0, param1, /* …, */ paramN) {
  // statements
  console.log(`anonymous async function expression IIFE`)
  return Promise.resolve(`anonymous async function expression IIFE`)
})().then(msg => {
  console.log(`anonymous msg =`, msg)
  return msg;
})
anonymousIIFE.then(str => console.log(`anonymous str =`, str))

// named async function expression IIFE
const namedIIFE = (async function iife(param0, param1, /* …, */ paramN) {
  // statements
  console.log(`named async function expression IIFE`)
  return Promise.resolve(`named async function expression IIFE`)
})().then(msg => {
  console.log(`named msg =`, msg)
  return msg;
})
namedIIFE.then(str => console.log(`named str =`, str))

Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Async

The async function declaration creates a binding of a new async function to a given name.
The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.

简化 Promise 链式调用的显式配置,写法更优雅

function resolveAfter2Seconds() {
  return new Promise((resolve) => {
    console.log('wait1...');
    setTimeout(() => {
      console.log('wait3...', typeof resolve);
      resolve('resolved');
      console.log('wait4...');
    }, 2000);
    console.log('wait2...');
  });
}

// async function declaration ✅
async function asyncCall() {
  console.log('calling 0 ');
  const result = await resolveAfter2Seconds();
  console.log(`result 5`, result);
}

asyncCall();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

The async function keywords can be used to define an async function inside an expression.

// async function expression

function resolveAfter2Seconds(x) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

// async function expression assigned to a variable
const add = async function (x) {
  const a = await resolveAfter2Seconds(20);
  const b = await resolveAfter2Seconds(30);
  return x + a + b;
};

add(10).then((v) => {
  console.log(v); // prints 60 after 4 seconds.
});

// async function expression used as an IIFE
(async function (x) {
  const p1 = resolveAfter2Seconds(20);
  const p2 = resolveAfter2Seconds(30);
  return x + (await p1) + (await p2);
})(10).then((v) => {
  console.log(v); // prints 60 after 2 seconds.
});


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function*

Await


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

Zero Width Joiner / 零宽连接器

零宽字符 / Zero Width Space

U+200D
Zero width joiner
<ZWJ>
Placed between characters that would not normally be connected in order to cause the characters to be rendered using their connected form in certain languages.

image

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion

https://en.wikipedia.org/wiki/Zero-width_joiner

👨‍👩‍👦‍👦

组合 emoji 字符串反转,防止分开

// 

Man] [ZWJ] [Woman] [ZWJ] [Boy] => 👨‍👩‍👦 => Family: Man, Woman, Boy

https://en.wikipedia.org/wiki/Zero-width_joiner

refs

https://javascript.info/async-await



©xgqfrms 2012-2021

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!