--- title: async function slug: Web/JavaScript/Reference/Statements/async_function translation_of: Web/JavaScript/Reference/Statements/async_function ---
{{jsSidebar("Statements")}}
Việc tạo hàm với câu lệnh async function sẽ định nghĩa ra một hàm không đồng bộ (asynchronous function) - hàm này sẽ trả về một object {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}

Các hàm không đồng bộ sẽ hoạt động trong một thứ tự tách biệt so với phần còn lại của đoạn code thông qua một event loop, trả về kết quả là một {{jsxref("Promise")}} tiềm ẩn. Nhưng cú pháp và cấu trúc của đoạn code mà sử dụng các hàm async function trông cứ như những hàm đồng bộ tiêu chuẩn.

Bạn cũng có thể định nghĩa các async function với một {{jsxref("Operators/async_function", "async function expression", "", 1)}}.

{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}

Cú pháp

async function name([param[, param[, ...param]]]) {
   statements
}

Các thông số

name
Tên của function.
param
Tên của một đối số được truyền vào function.
statements
Các câu lệnh bao hàm phần thân của function.

Giá trị trả về

Một Promise, cái mà sẽ được giải quyết với giá trị được trả về bởi async function, hoặc được đẩy ra ngoài với một exception không được bắt lại bên trong hàm async function.

Mô tả

Một hàm async có thể bao gồm một biểu thức {{jsxref("Operators/await", "await")}}, biểu thức này sẽ tạm dừng việc thực thi của hàm async để chờ cho Promise's resolution được truyền vào, sau đó tiếp tục việc thực thi của hàm async and evaluates as the resolved value.

Từ khóa await chỉ có hiệu lực bên trong hàm async. Nếu bạn sử dụng nó bên ngoài phần thân của hàm async, bạn sẽ nhận một SyntaxError.

Trong lúc hàm async tạm dừng, hàm được gọi sẽ tiếp tục chạy. (hàm mà nhận được Promise tiềm ẩn được trả về bởi hàm async).

Mục đích của async/await là để đơn giả hóa việc sử dụng các promises một cách đồng bộ, và để triển khai một số hoạt động trên một nhóm của các Promises. Nếu Promises là tương tự như các callback có cấu trúc, async/await là tương tự với kết hợp các generators và promises.

Ví dụ

Async functions và thứ tự của việc thực thi

function resolveAfter2Seconds() {
  console.log("starting slow promise")
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("slow")
      console.log("slow promise is done")
    }, 2000)
  })
}

function resolveAfter1Second() {
  console.log("starting fast promise")
  return new Promise(resolve => {
    setTimeout(function() {
      resolve("fast")
      console.log("fast promise is done")
    }, 1000)
  })
}

async function sequentialStart() {
  console.log('==SEQUENTIAL START==')

  // 1. Execution gets here almost instantly
  const slow = await resolveAfter2Seconds()
  console.log(slow) // 2. this runs 2 seconds after 1.

  const fast = await resolveAfter1Second()
  console.log(fast) // 3. this runs 3 seconds after 1.
}

async function concurrentStart() {
  console.log('==CONCURRENT START with await==');
  const slow = resolveAfter2Seconds() // starts timer immediately
  const fast = resolveAfter1Second() // starts timer immediately

  // 1. Execution gets here almost instantly
  console.log(await slow) // 2. this runs 2 seconds after 1.
  console.log(await fast) // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
}

function concurrentPromise() {
  console.log('==CONCURRENT START with Promise.all==')
  return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
    console.log(messages[0]) // slow
    console.log(messages[1]) // fast
  })
}

async function parallel() {
  console.log('==PARALLEL with await Promise.all==')

  // Start 2 "jobs" in parallel and wait for both of them to complete
  await Promise.all([
      (async()=>console.log(await resolveAfter2Seconds()))(),
      (async()=>console.log(await resolveAfter1Second()))()
  ])
}

// This function does not handle errors. See warning below!
function parallelPromise() {
  console.log('==PARALLEL with Promise.then==')
  resolveAfter2Seconds().then((message)=>console.log(message))
  resolveAfter1Second().then((message)=>console.log(message))
}

sequentialStart() // after 2 seconds, logs "slow", then after 1 more second, "fast"

// wait above to finish
setTimeout(concurrentStart, 4000) // after 2 seconds, logs "slow" and then "fast"

// wait again
setTimeout(concurrentPromise, 7000) // same as concurrentStart

// wait again
setTimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"

// wait again
setTimeout(parallelPromise, 13000) // same as parallel

await và xử lý song song

In sequentialStart, execution suspends 2 seconds for the first await, and then another second for the second await. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.

In concurrentStart, both timers are created and then awaited. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
However, the await calls still run in series, which means the second await will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.

If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()]), as shown in the parallel example.

async/await vs Promise.then and error handling

Most async functions can also be written as regular functions using Promises. However, async functions are less tricky when it comes to error handling.

Both concurrentStart and concurrentPromise are functionally equivalent:

It is, however, still possible for async functions to mistakenly swallow errors.

Take, for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not propagate.

While the parallelPromise example seems simpler, it does not handle errors at all! Doing so would require a similar return Promise.all([]).

Rewriting a Promise chain with an async function

An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it splits the function into many parts. Consider the following code:

function getProcessedData(url) {
  return downloadData(url) // returns a promise
    .catch(e => {
      return downloadFallbackData(url)  // returns a promise
    })
    .then(v => {
      return processDataInWorker(v)  // returns a promise
    })
}

it can be rewritten with a single async function as follows:

async function getProcessedData(url) {
  let v
  try {
    v = await downloadData(url)
  } catch(e) {
    v = await downloadFallbackData(url)
  }
  return processDataInWorker(v)
}

In the above example, there is no await statement after the return keyword, because the return value of an async function is implicitly wrapped in {{jsxref("Promise.resolve")}}.

return await promiseValue vs. return promiseValue

The implicit wrapping of return values in {{jsxref("Promise.resolve")}} does not imply that return await promiseValue is functionally equivalent to return promiseValue.

Consider the following rewrite of the above code. It returns null if processDataInWorker rejects with an error:

async function getProcessedData(url) {
  let v
  try {
    v = await downloadData(url)
  } catch(e) {
    v = await downloadFallbackData(url)
  }
  try {
    return await processDataInWorker(v)  // Note the `return await` vs. just `return`
  } catch (e) {
    return null
  }
}

Writing return processDataInWorker(v) would have caused the {{jsxref("Promise")}} returned by the function to reject, instead of resolving to null if processDataInWorker(v) rejects.

This highlights the subtle difference between return foo; and return await foo;return foo immediately returns foo and never throws, even if foo is a Promise that rejects. return await foo will wait for foo to resolve or reject if it's a Promise, and throws before returning if it rejects.

Specifications

Specification
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}

Browser compatibility

{{Compat("javascript.statements.async_function")}}

See also