Files
Hexo-Butterfly/source/_posts/异步JavaScript.md
T

313 lines
9.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 异步JavaScript
date: 2021-10-17 11:33:22
tags:
- JavaScript
- 前端
description: 异步JavaScript
top_img: >-
https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg
cover: >-
https://upload.wikimedia.org/wikipedia/commons/9/99/Unofficial_JavaScript_logo_2.svg
categories:
- 前端
- JavaScript
abbrlink: 110858fe
update: 2021-10-17 11:41:30
---
# 什么是异步执行?
我们编写的JS程序天生就是异步的
我们将函数作为参数传递给其他函数,以便当我们知道预期发生的事情时,可以“稍后回调”。
回调在事件驱动编程中是一个非常强大的特性。
为什么你认为在JavaScript语言中有能力将回调函数作为参数传递给其他函数,如JS中的addEventListener和setTimeout是有用的?
![asynchronous](/images/asynchronous.png)
# 同步与异步
```javascript
(function () {
...
function init() {
console.log('page loaded');
qs('button').addEventListener('click', clickHandler);
showMenu();
}
function showMenu() {
id('menu').classList.remove('hidden');
}
function clickHandler() {
/* Code Here */
}
}) ();
```
这基本上是同步的,但有点介于两者之间
clickHandler不能保证被调用,所以它被推入异步
# 如果
我们没有监听事件?
```javascript
let myBtn = qs('button:nth-child(1)');
while (!myBtn.clicked) {
/* Code Here */
}
console.log('"终于等到被点击了"');
let myBtn2 = qs('button:nth-child(2)');
while (!myBtn2.clicked) {
/* Code Here */
}
console.log('"第二次点击"');
```
- 以上的代码没有办法执行(并且会让你的浏览器崩溃)
- 我们在等代码运行的时候什么也做不了
- 但是同步执行逻辑很好
# 披萨类比
我在之前的那个[异步执行](https://www.angluareportfolio.pw/141d93dd)的文章说到一个关于披萨的例子,我们在这里还是会用到同一个例子。
在餐馆,你遵循以下步骤:
- 请求菜单
- 订一个披萨
- 检查披萨
- 吃披萨
- 支付披萨
在前一步完成之前,每一步都不能继续。
```javascript
requestMenu();
// twiddle thumbs
orderPizza();
// twiddle thumbs
verifyPizza();
// twiddle thumbs
eatPizza();
// twiddle thumbs
payForPizza();
```
# 回调
回调在事件驱动编程中是一个非常强大的特性。
- 比例:在电话答录机上留下你的电话号码
为什么你认为在JavaScript语言中有能力将回调函数作为参数传递给其他函数,如JS中的addEventListener和setTimeout是有用的?
- 使异步执行!
# (再次)回调到回调
我们可以将所有这些步骤想象成一系列回调,具体取决于它们之前的事件。
我们要等多久才能执行这些任务?
我们不知道!
```javascript
function order() {
setTimeout(function () {
makeRequest("Requesting menu...");
setTimeout(function() {
makeRequest("Ordering pizza...");
setTimeout(function() {
makeRequest("Checking pizza...");
setTimeout(function () {
makeRequest("Eating pizza...");
setTimeout(function() {
makeRequest("Paying for pizza...");
setTimeout(function () {
let response = makeRequest("Done! Heading home.");
console.log(response);
})
})
})
})
})
})
}
```
以上的这段代码,属于是一个叫回调地狱,因为代码在重复运行,所以我们也不知道代码什么时候停止运行。所以,在我们写代码的时候,尽量不要写“回调地狱”。
# 回调的解决方案
我们上一个部分写的那个“回调地狱”的解决方案,其实有一个方法可以去解决。我们可以尝试这个试试看:
```javascript
orderPizza()
.then(verify)
.then(eat)
.then(pay)
.catch(badPizza);
```
# Promise
什么是Promise?
Promise算是一种契约:
- 即将会发生的事件
- 可以发生多个事件
- 抓住错误
只能从待定到完成或拒绝(没有反悔)
![promise](/images/promise.png)
例如:“我保证等你回到你的座位”
- 等待:等我的披萨
- 满足:披萨来了!!
- 被拒绝: 厨房的奶酪用完了。
更多的Promise,可以看一些这个[Promise文档](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise)
# 创建一个Promise
| 函数 | 描述 |
| --- | --- |
| let promiseObj = new Promise(executorFn) | 使用executorFn创建一个新的Promise对象 |
| promiseObj.then(onFulfilled, onRejected) | 当Promise被实现(被拒绝)时调用onFulfilled(onReject)函数 |
| promiseObj.catch(callback) | 如果Promise被拒绝(或发生错误),则调用回调函数 |
```javascript
function executionFn(resolve, reject) { //回调作为一个参数
...
if (conditionMet) {
resolve(); // 通过Promise传递对象
} else {
reject(); // 通过Promise传递对象
}
}
```
你可以定义这个函数并将其传递给Promise构造函数
使用then和catch在Promise对象上串联动作
# 披萨例子
我们可以传递一个值来解析。。。
```javascript
function orderExecutor(resolve, reject) {
console.log('making our pizza...');
setTimeout(function () {
resolve("Here's your pizza!");
}, 5000);
}
let orderPizza = new Promise (orderExecutor);
orderPizza.then(function (value) { console.log(value); });
```
这个值传递给then函数
传递给then的函数可以将值传递给下一个then回调函数。
```javascript
function eat(value) {
return value + ", and now it's gone";
}
let orderPizza = new Promise (orderExecutor);
orderPizza.then(eat).then(function (value) { console.log(value); });
```
你还可以返回其他promise,这些promise将暂停下一个then回调的执行,知道它被解决
```javascript
function eatExecutor(resolve, reject) {
console.log('eating our pizza...');
setTimeout(resolve, 3000)
}
function eat() {
return new Promise (eatExecutor);
}
let orderPizza = new Promise(orderExecutor);
orderPizza.then(eat).then(function () { console.log('Paying the bill!'); });
```
# 还是异步
```javascript
function orderExecutor(resolve, reject) {
console.log('Pizza ordered...');
resolve("Here's your pizza!");
}
let orderPizza = new Promise(orderExecutor);
orderPizza.then(function (value) { console.log(value); });
console.log("Waiting for my pizza!");
```
# 拒绝一个披萨
```javascript
function orderExecutor(resolve, reject) {
console.log('Pizza ordered...');
setTimeout(function() {
reject("Ran out of cheese. Can you believe it?");
}, 2000)
}
let orderPizza = new Promise(orderExecutor);
orderPizza
.then(function () { console.log("Woohoo, let's eat!"); })
.catch(function (value) { console.log(value); });
```
# 真的是这样使用Promise函数吗?
- (现在)为了让事情变得更简单
- 计时器和数字不是一个典型的/必要的Promise用例
- Promise用于当我们不想停止主要的执行流程,但正在处理一个需要不确定的时间量任务时
- 例子:从服务器请求信息
- 如果服务器宕机了怎么办?如果返回的结果有错误怎么办?如果我的请求提供了不准确的信息,该怎么办?
# 不确定性
有些操作花费的时间位置,或者失败的记录也不是很小
- 文件I/O
- 数据库
- HTTP请求
- 资源不存在(404)
- 响应时间过长或服务器宕机
- 糟糕的网络链接
无论这些请求是成功还是失败,我们任然希望做出一些反应
# then和catch返回Promise
```javascript
function executor(resolve) {
resolve('Woohoo!');
}
let myPromise = new Promise(executor);
let thenPromise = myPromise.then(console.log);
let catchPromise = myPromise.catch(console.error);
console.log(thenPromise instanceof Promise); //true
console.log(catchPromise instanceof Promise); //true
console.log(myPromise === thenPromise); //false
console.log(myPromise === catchPromise); //false
console.log(thenPromise === catchPromise); //false
```
then和catch返回Promise
```javascript
function executor(resolve) {
resolve('Woohoo!');
}
function processStr(val) {
return val.toLowerCase().replace('!', '');
}
let myPromise = new Promise(executor);
let thenPromise = myPromise.then(processStr);
console.log(thenPromise);
```
processStr返回一个支付穿,然后将其转换为一个Promise,该Promise会立即使用值"woohoo"进行解析。
```javascript
function executor(resolve) {
resolve('Woohoo!');
}
function processStr(val) {
return new Promise(function (resolve)) {
setTimeout(function () {
resolve(val.toLowerCase().replace('!', ''));
}, 5000);
};
}
let myPromise = new Promise(executor);
let thenPromise = myPromise.then(processStr);
console.log(thenPromise);
```
现在,Promise是属于“等待”(PENDING),在processStr返回的promise被解析前不会被解析。