-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Promise & Async/Await #6
Comments
Promise的all方法:提供了并行执行多个异步操作的能力,并且在所有异步操作执行完后执行回调。
Promise的race方法:可以用race给某个异步请求设置超时时间,并且在超时后执行相应的操作。
|
async/await使得异步代码看起来像同步代码,再也没有回调函数,代码优雅可读性好
async/await如果想并行执行多个异步操作(通常发生在发送请求时,避免不必要的等待):
2.使用中间变量
异常处理:
对比举例:
使用async/await的话,代码会变得异常简单和直观
|
手写promise1.0版只实现了成功回调的处理
|
手写promise2.0版成功和失败回调的处理,还没实现链式处理
|
手写promise3.0版.then的链式调用
|
链式嵌套 promise 的执行顺序: 执行完当前 promise ,会把紧挨着的 then 放入 microtask 队尾, |
Promise 对象用于表示一个异步操作的最终状态(完成或失败),以及该异步操作的结果值。
它允许你为异步操作的成功和失败分别绑定相应的处理方法(handlers)可以将异步操作队列化,按照期望的顺序执行,返回符合预期的结果
一个 Promise有以下几种状态:
pending: 初始状态,既不是成功,也不是失败状态。

fulfilled: 意味着操作成功完成。
rejected: 意味着操作失败。
状态一旦改变,就不会再变。创造promise实例后,它会立即执行。
从表面上看,Promise只是能够简化层层回调的写法,而实质上,Promise的精髓是“状态”,用维护状态、传递状态的方式来使得回调函数能够及时调用,它比传递callback函数要简单、灵活的多
参考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
https://developers.google.com/web/fundamentals/primers/promises
The text was updated successfully, but these errors were encountered: