Promise 解释
The Promise object is used for deferred and asynchronous computations.
Promise 语法
1 | new Promise(executor); |
Promise 结构
Constructor
1 | new Promise(function(resolve, reject) {}); |
resolve(thenable)
Your promise will be fulfilled/rejected with the outcome of thenable
resolve(obj)
Your promise is fulfilled with obj
reject(obj)
Your promise is rejected with obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error. Any errors thrown in the constructor callback will be implicitly passed to reject(). Instance Methods
promise.then(onFulfilled, onRejected)
onFulfilled is called when/if “promise” resolves. onRejected is called when/if “promise” rejects. Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. Both callbacks have a single parameter, the fulfillment value or rejection reason. “then” returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. If an error is thrown in the callback, the returned promise rejects with that error.
promise.catch(onRejected)
Sugar for promise.then(undefined, onRejected)
简单例子
1 | var p = new Promise(function(resolve, reject) { |
接受参数的例子
1 | function get(url) { |
还可以用 Promise.catch()
捕获错误
1 | function get(url) { |
链式请求
1 | get('es.js').then(function(response) { |
异步请求例子
1 | function get(url) { |
Q
_Q_ 指的是 kriskowal/q,一个提供 Promise 特性的组件。
1 | var fs = require('fs'); |