async...await
In JavaScript, we need to handle asynchronous functions in JavaScript’s single-threaded world. Often, developers will use promises to handle asynchronous functions. There are two ways to handle promises: async/await or the .then method.
在JavaScript中,我们需要在JavaScript的单线程世界中处理异步函数。 开发人员通常会使用Promise处理异步功能。 有两种处理诺言的方法:async / await或.then方法。
What is a promise? A promise is NOT A FUNCTION. A promise is an OBJECT. To create a promise, we pass in an “executor” function into JavaScript’s constructor function using the “new” keyword. The “executor” is just a fancy name for a regular function that will be passed into the promise constructor. The executor contains the logic for an operation you want completed. After the promise is created, the promise will automatically call the executor. This executor has two arguments dubbed “resolve” and “reject” which are callback functions.
什么是诺言? 许诺不是功能 。 一个诺言是一个对象 。 为了创建承诺,我们使用“ new”关键字将“ executor”函数传递到JavaScript的构造函数中。 “执行程序”只是常规函数的奇特名称,它将被传递到promise构造函数中。 执行程序包含要完成的操作的逻辑。 创建承诺后,承诺将自动调用执行程序。 该执行程序有两个称为回调函数的参数,分别称为“解决”和“拒绝”。
The promise has two properties called “state” and “result” which are initially set to “pending” and “undefined,” respectively. Once the operation is complete, we use either the “resolve” or “reject” callback to change the state to “fulfilled” or “rejected” and set the result. This result is passed on to .then, .catch, and .finally which are named “consuming functions.”
许诺有两个属性,分别称为“状态”和“结果”,最初分别设置为“待处理”和“未定义”。 一旦操作完成,我们将使用“解决”或“拒绝”回调将状态更改为“已实现”或“已拒绝”并设置结果。 该结果将传递给.then,.catch和.finally,它们被称为“使用函数”。
Chaining: The consuming functions can be chained to our promise. In our example below, since the condition was met/true, the resolve() was called so the .then() function received the result “Promise is resolved successfully.” Had the condition failed, reject() would be called and the .catch() function would receive an error as the result.
链接:消费功能可以链接到我们的承诺。 在下面的示例中,由于条件满足/为真,因此调用了resolve(),因此.then()函数收到结果“承诺已成功解决”。 如果条件失败,则将调用reject(),并且.catch()函数将收到错误结果。
const myPromise = new Promise((resolve, reject) => {
let condition = true;if (condition) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});myPromise
.then((result) => console.log(result))
.catch((result) => console.log(result));
Why should we use promises? To prevent us from callback hell (too many nested callbacks). Before promises, you would have to write callback functions for
我们为什么要使用承诺? 为了防止我们回调地狱(嵌套的回调太多)。 在答应之前,您将必须为
Asynchronous Functions: Promises are most commonly used with asynchronous functions. In most cas