Async/Await:简介
在执行异步操作时,回调和 Promise 非常出色。Promise 比回调有所改进,并提供了扁平化的代码语法,尤其是在链式 Promise 操作方面。Promise 上的运算符(例如allSettled
、any
和 )then
使catch
编写复杂的异步操作变得更加容易。
ES7 中引入了 Async/Await,旨在使 Promise 的语法更加简洁。本质上,async/await 就是 Promise;它们在这些关键字下提供了一个很好的抽象层。
异步
async
关键字可以用于任何函数(声明、表达式、回调或任何其他位置)的前面。这意味着该函数始终会返回一个 Promise。除 Promise 之外的任何返回值都将包装在已解析的 Promise 中。
async function foo() {
return "Parwinder" // returning a string but `async` will ensure it is wrapped in a promise
}
foo().then((data) => { // we can safely use then because async function foo returns a promise
console.log(data); // Parwinder
})
我们可以在函数中返回一个 Promise foo
,它仍然可以工作。不过,这没有必要。
async function foo() {
return Promise.resolve("Parwinder")
}
foo().then((data) => {
console.log(data); // Parwinder
})
等待
await
关键字使 JavaScript 等待 Promise完成并返回其结果。它只能在函数内部使用async
。
async function foo() {
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
}, 2000);
});
// will not move to the next line until myPromise resolves/rejects
const name = await myPromise;
// the execution pauses (or awaits) for the promise
console.log(name); // Parwinder
}
foo();
正如您在上面的示例中看到的,await
与相比,它提供了更清晰的语法Promise.then
。