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

发布时间 2023-08-31 21:58:38作者: xgqfrms

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

Async vs Promise

demos

(? 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

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.
});


// async function `name`
async function name(param0) {
  statements
}

async function name(param0, param1) {
  statements
}

async function name(param0, param1, /* …, */ paramN) {
  statements
}

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

refs

https://javascript.info/async-await



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

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