async 过程的事实标准:promise a+ ( when ,then style js)
访问量: 2837
refer to: https://promisesaplus.com
一句话: async_call('/some_url').then(成功,失败).then(成功, 失败) ...
两个特点: 1. 把异步调用变成了顺序调用的写法。 2. 使用了 chaining call.
promise a+, 官方的解释是:An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
promise: 一个异步调用(A promise represents the eventual result of an asynchronous operation)
then: 紧跟一个 promise 之后,用来声明 promise中的 callback, 与之交互 (The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled )
术语表:
promise: 返回的结果,可以调用then方法。
thenable: 定义了 then 方法的object, function
value, exception .reason. 略。
1. Promise的状态:
pending:
可以转换到 fullfilled 或者 rejected状态。(例如 刚发起了request,但是尚未收到远程返回的结果)
fullfilled:
状态稳定不变,而且有个值 (例如:发起request之后,收到了服务器返回的值)
rejected
操作被拒绝(比如说 远程 返回400, 302, 404, 50x), 状态稳定不变,可能有个reason.
2. Then
每个promise 都必须有 then方法。 比如说:
promise.then( on_full_filled, on_rejected)
on_full_filled, on_rejected 都是函数, 可以省略。 最多只能被调用一次,不能调用多次。 都是在对应的状态出现后(full_filled, rejected) 之后才被调用。
可以对promise 有多次then的调用。 比如;
promise.then(full1, rejected_1).then(full2, rejected_2).then( full_filled_3, rejected_3) , 前面的then有一个reject, 那么后面的then的reject就会依次全部被调用。 例如:
failed: reject1 -> rejected_2 -> rejected_3
每个then返回的 都是一个promise, 例如;
promise2 = promise1.then( full_filled_1, rejected_1)
如果 full_filled_1 和 rejected_1 都未定义,那么 promise2 与 promise1 返回的 value, reason 是一样的。
详细的解析过程,略了。。。有兴趣的同学自行查看吧。
原文档虽然略缩,但是在语义上是特别周密的。
p.s.
业内实现了 promise 标准的有很多: jQuery’s Deferred, Microsoft’s WinJS.Promise, when.js, q, and dojo.Deferred.