Q promise API简单翻译
详细API:https://github.com/kriskowal/q/wiki/API-Reference
Q提供了promise的一种实现方式,现在在node中用的已经比较多了。因为没有中文的api,我就简单翻译下吧。鄙人不才,欢迎拍砖。。。
一、Core Promise Methods
1、promise.then(onFulfilled, onRejected, onProgress)
这个就不说了吧。
2、promise.catch(onRejected)
其等同于:promise.then(undefined, onRejected)意思是当catch到异常时的执行。
3、promise.progress(onProgress)
等同于:promise.then(undefined, undefined, onProgress)???
4、promise.finally(callback)
类似与trycatch中的finally,不管成功与否都会执行callback,主要用在关闭数据库、关闭服务,删除一个无用的键等。finally后会返回这个promise执行完完全一样的promise(包括失败和成功),但是如果callback也返回promise,那么前者会等到后者出现后才进行解析。
5、promise.done(onFulfilled, onRejected, onProgress)
这个方法很像痛恨,但是如果有一个未处理的rejection或者其onrejected未定义,这个方法就有用了。官方的解释是,这个方法可以用于终结promise链,以防止promise的继续传递。
二、Promise-for-Object Methods
这类方法较简单:
1、promise.get(propertyName)
等价如下,不解释:
promise.then(function (o) { return o[propertyName]; });2、promise.post(methodName, args)
等价如下:不解释:
promise.then(function (o) { return o[methodName].apply(o, args); });3、promise.invoke(methodName, ...args)
与上一个类似,不解释,区别就是参数不是数组,而是直接赋值进去。
4、promise.keys()
等价如下:不解释:
promise.then(function (o) { return Object.keys(o); });三、Promise-for-Function Methods
1、promise.fbind(...args) (deprecated)
没看明白啥意思,
2、promise.fapply(args)
等价于:
promise.then(function (f) { return f.apply(undefined, args); });意思就是promise返回的是函数,然后调用它。
3、promise.fcall(...args)
四、Promise-for-Array Methods
1、promise.all()
这个方法很有用,其接受一个promise数组,,只有当数组中的每个promise都执行成功,才会成功并将结果以数组的形式返回。当有一个promise失败,即失败。总之是为了确保数组中的promise都成功。典型例子:
Q.all([getFromDisk(), getFromCloud()]).done(function (values) { assert(values[0] === values[1]); // values[0] is fromDisk and values[1] is fromCloud });2、promise.allSettled()
啊啊啊啊。。。不完全懂!
3、promise.spread(onFulfilled, onRejected)
这个方法和then类似,但是,当一个数组的promise有一个失败时,其将会以第一个失败的promise的reject原因来执行onRejected。。。所以其与all配合使用较多,如:
Q.all([getFromDisk(), getFromCloud()]).spread(function (diskVal, cloudVal) { assert(diskVal === cloudVal); }).done();五、Utility Methods
1、promise.thenResolve(value)
等价于:promise.then(function () { return value; }).
2、promise.thenReject(reason)
等价于:promise.then(function () { throw reason; }).
3、promise.timeout(ms, message)
正常情况下 会正常返回promise结果,但是如果promise在ms毫秒前没有执行完,就会返回一个message的rejection,如果message没有给,就返回:"Timed out after " + ms + " ms".如:
promise.timeout(10000).then( function (result) { // will be called if the promise resolves normally console.log(result); }, function (err) { // will be called if the promise is rejected, or the 10 second timeout occurs console.log(err); } );4、promise.delay(ms)
注意,这里是,只有当ms毫秒后promise才执行完时才会正常的返回正常的值。
5、Q.delay(ms)
Q.delay(150).then(doSomething);等价于settimeout
六、Promise Creation
1、Q.defer()
Returns a "deferred" object with a:
promise property
resolve(value) method
reject(reason) method
notify(value) method
makeNodeResolver() method
Q promise API简单翻译
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70170.html