本问答旨在明确回答以下问题:
async
, await
JavaScript 中的关键字以及它们与异步函数的关系如何? 要遵循答案,需要以下先决条件:
最佳答案
介绍
JavaScript 有一个异步模型。每当异步操作完成时,您通常希望之后执行一些代码。第一个回调是
经常用来解决这个问题。但是,当使用多个异步元素编写代码时,使用回调会出现问题。因为当您将多个回调相互嵌套时,代码变得难以快速维护。这种反模式称为 回调 hell .
promise
Promises 解决了嵌套回调中出现的许多问题。 Promise 的一个关键属性是它们可以使用 很好地链接在一起。 promise 链 .这允许比回调更简洁的语法和更容易的错误处理。这是一个例子:
const randomProm = new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve('Succes');
} else {
reject('Failure');
}
});
// Promise chain
randomProm
.then((value) => {
console.log('inside then1');
console.log(value);
return value
}).then((value) => {
console.log('inside then2');
console.log(value);
return value
}).catch((value) => {
console.log('inside catch');
console.log(value);
});
异步函数
异步函数建立在 Promise 之上。它们允许更方便地使用 Promise。异步函数具有以下属性:
async
在函数声明/表达式将函数转换为异步函数之前。顾名思义,异步函数是异步执行的。 Promise.resolve(returnval)
中.但是,当异步函数内部抛出 Uncaught Error 时,它会将返回值包装在 Promise.catch(returnval)
中。 . await
可以在任何 promise 之前使用的关键字。 await
使 JS 代码执行停止,直到 promise 被解决。即,在异步函数内的任何进一步代码执行之前,必须履行或拒绝 promise 。 await
要么返回已履行的 promise 的值,要么在被拒绝的 promise 的情况下抛出错误。我们可以使用常规的 try-catch 来捕获错误。 让我们用一些例子来澄清这一点:
示例 1:
const randomProm = new Promise((resolve, reject) => {
if (Math.random() > 0.5) {
resolve("Succes");
} else {
reject("Failure");
}
});
// async keyword creates an async function which returns a promise
async function ansyncExample() {
try {
const outcome = await randomProm;
console.log(outcome);
} catch (error) {
console.log(error);
}
// This return value is wrapped in a promise
return 'AsyncReturnVal';
}
// ansyncExample() returns a promise, we can call its corresponding then method
ansyncExample().then((value) => {
console.log(value);
});
console.log('I get executed before the async code because this is synchronous');
示例 2:
// We can use async in function expressions
const randomProm = async () => {
if (Math.random() > 0.5) {
// This value is wrapped in Promise.resolve()
return "Succes";
} else {
// This value is wrapped in Promise.reject()
throw "Failure";
}
};
// async keyword creates an async function which returns a promise
async function ansyncExample() {
// randomProm is async fuction which returns a promise which we can await
return await randomProm();
}
// ansyncExample() returns a promise, we can call its corresponding then/catch method
ansyncExample()
.then((value) => {
console.log("Inside then");
console.log(value);
})
.catch((value) => {
console.log("Inside catch");
console.log(value);
});
console.log("I get executed before the async code because this is synchronous");
何时使用异步函数
理论上,每次使用 Promise 时都可以使用 async 函数。然而,当有多个异步操作返回 Promise 并且相互依赖时,异步函数的威力才真正开始发挥作用。
因为 async 函数允许我们以同步的方式编写基于异步 promise 的代码。 代码仍然是异步的,但我们现在可以以同步方式读取它 .它比 promise 链更容易阅读和维护,因此可以更好地扩展(IMO)。
这是一个很好的可读性的例子:
async function ansyncExample() {
try {
// 3 async operations which depend on each other
const firstValue = await firstAsyncFunc();
const SecondValue = await secondAsyncFunc(firstValue);
const ThirdValue = await thirdAsyncFunc(SecondValue);
} catch (error) {
console.log(error);
}
return ThirdValue;
}
关于javascript - JavaScript 中的异步函数是什么? JavaScript 中的 "async"和 "await"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62196932/