You Don't Know JS: Async & Performance(第3章, Promises)(未看)

Chapter 3: Promises

But what if we could uninvert that inversion of control? What if instead of handing the continuation of our program to another party, we could expect it to return us a capability to know when its task finishes, and then our code could decide what to do next?

most new async APIs being added to JS/DOM platform are being built on Promises. 

⚠️:

本章immediately这个词非常常见,意思从Job queue behavior的角度是立即地,并非严格地同步的now sense

What Is a Promise?

面对新技术或模式,如果只看代码来了解和学习,一些抽象概念就会失去。

作者在展示代码前,想要完全的解释什么是Promise概念上地。希望这些可以指导你更好地探索集成的Promise理论进入你的异步流动。

出于这个想法,让我们看2个不同的类比。什么是promise。

  1. 未来值
  2. 现在稍后值

Future Value

想象这个场景:在一个快餐馆下一个订单,并支付1.47。我制造了一个request并等待一个value返回(食品)。我开始了一个transaction.

但我需要等待食物烹饪。(异步)

我拿着收款小条,上面有一个订单号码。这个订单号码是一个“I owe you”promise,确保我肯定会得到食品。

小条和订单号码代表:我会在未来某个时刻得到一个value(食品)。 这是一个承诺Promise.

当等待上餐的时候,我做其他的事情。我把订单号当成食品的占位符。这个占位符让这个value time是独立地。它是一个未来的值。 Future Value

当我听到“Order 113!”, 我走向柜台,用小条交换食品。

即:(一旦我的未来值准备好了,我用我的value-promise来换这个value)

但是有其他的结果。 我听到我的订单号,但是当我要交换小条时,服务员告诉我是“抱歉,食品已经卖光了!”(这表面结果可能是成功也可能是失败

⚠️在代码中,不会如例子这样简单,有可能这个订单号码永远不会被喊道,导致我们进入一个无限期的未解决状态。

Values Now and Later

在开始介绍Promise如何工作时,先说下callbacks! -- how to handle these future values.

(不是很懂)

var x, y = 2;

console.log( x + y ); // NaN  <-- because `x` isn't set yet

因为x未分配值,所以运算失败。

使用回调函数处理,“把x,y相加,如果它们中有一个未赋值,就等待,直到它们都有值了, 把它们相加”

 to consistently handle both now and later, we make both of them later: all operations become async.

 It's just a first tiny step toward realizing the benefits of reasoning about future values without worrying about the time aspect of when it's available or not.

Promise Value

这里如何通过Promise来表示x+y。

function add(xPromise,yPromise) {
    // `Promise.all([ .. ])` 接受一个数组的promises,,等待它们都完成后,返回一个新promise。
    return Promise.all( [xPromise, yPromise] )

    //当promise被解决,就可以把收到的value(x, y)相加
.then( function(values){ // `values` is an array of the messages // 从刚才的已解决的promises. return values[0] + values[1]; } ); } // `fetchX()` and `fetchY()` return promises for // their respective values, which may be ready // *now* or *later*. add( fetchX(), fetchY() ) // we get a promise back for the sum of those // two numbers. // now we chain-call `then(..)` to wait for the // resolution of that returned promise. .then( function(sum){ console.log( sum ); // that was easier! } );

像上文的食品订单,一个Promise可以是被拒绝的(也是一个结果,promise类似保证给你一个结果,未必令你满意)。一个拒绝value被叫做rejection reason! 既可能是程序逻辑直接设置的,也可能是从一个运行时间例外暗示地设置。

.then()就是处理Promise的结果的, 既有fulfillment handler, 也有rejection handler.

因为Promises封装了时间依赖状态the time-dependent state ---等待满足或拒绝这个潜在的value--从外部,因此Promises可以被composed(combined, 比如x和y做加法运算)

一旦一个Promise被解决,它就是一个不变的值,如果需要可以多次被observed。

Promises是一个方便的可重复的机制用于封装和组织furture value。

Promises are an easily repeatable mechanism for encapsulating and composing future values.

Completion Event

一个独立的Promise 表现如一个future values。

但是还可以从其他方面思考一个Promise的解决: 作为一个 控制流动机制--一个时间上的this-then-that--2个或多个步骤在一个异步task内。

假设调用一个函数foo(..)来执行一些tasks。我们无需知道它的内部细节。它可能立即完成tasks,也可能过一会。 我们仅仅需要知道当foo(..)完成后我们就可以进行下一个task了。也就是说我们需要一个foo()完成的通知,以便进行后面的工作。

在典型的JS方式内,如果你需要监听一个通知,you'd likely think of that in terms of events.(从事件的角度思考它).   所以我们要监听一个完成事件,它由foo()发出。                                                                                 

var evt = foo( 42 );

// let `bar(..)` listen to `foo(..)`'s completion
bar( evt );

// also, let `baz(..)` listen to `foo(..)`'s completion
baz( evt );

 

Promise "Events"

foo()创建了并返回了一个Promise实例,这个实例将会被传入bar和baz。

注意,是使用then()来注册一个then event。

(后面的暂停看!!!)

 


Thenable Duck Typing


 

Promise Trust

针对传统回调函数的trust问题的各类情况,Promise是如何解决的:

Calling Too Early

Calling Too Late

Promise Scheduling Quirks

Never Calling the Callback

Calling Too Few or Too Many Times

Failing to Pass Along Any Parameters/Environment

Swallowing Any Errors/Exceptions

Trustable Promise?

Trust Built


Chain Flow

  • Every time you call then(..) on a Promise, it creates and returns a new Promise, which we can chain with.
  • Whatever value you return from the then(..) call's fulfillment callback (the first parameter) is automatically set as the fulfillment of the chained Promise (from the first point).

Terminology: Resolve, Fulfill, and Reject

原理一大堆解释,也没看。)


Error Handling

Pit of Despair

Uncaught Handling

Pit of Success


Promise Patterns

Promise.race([ .. ])

Timeout Race

"Finally"

Variations on all([ .. ]) and race([ .. ])

Concurrent Iterations


Promise API Recap

new Promise(..) Constructor

Promise.resolve(..) and Promise.reject(..)

then(..) and catch(..)

Promise.all([ .. ]) and Promise.race([ .. ])


Promise Limitations

Sequence Error Handling

Single Value

Unwrap/Spread Arguments

Single Resolution

Inertia

Promise Uncancelable

Promise Performance


 

Review

原文地址:https://www.cnblogs.com/chentianwei/p/9774098.html