Bluebird-Core API
Posted 小彭博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Bluebird-Core API相关的知识,希望对你有一定的参考价值。
Promise.join
Promise.join( Promise<any>|any values..., function handler ) – -> Promise
For coordinating multiple concurrent discrete promises. While
is good for handling a dynamically sized list of uniform promises, .all
Promise.join
is much easier (and more performant) to use when you have a fixed amount of discrete promises that you want to coordinate concurrently. The final parameter, handler function, will be invoked with the result values of all of the fufilled promises. For example:
var Promise = require("bluebird"); var join = Promise.join; join(getPictures(), getComments(), getTweets(), function(pictures, comments, tweets) { console.log("in total: " + pictures.length + comments.length + tweets.length); });
var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var pg = require("pg"); Promise.promisifyAll(pg, { filter: function(methodName) { return methodName === "connect" }, multiArgs: true }); // Promisify rest of pg normally Promise.promisifyAll(pg); var join = Promise.join; var connectionString = "postgres://username:[email protected]alhost/database"; var fContents = fs.readFileAsync("file.txt", "utf8"); var fStat = fs.statAsync("file.txt"); var fSqlClient = pg.connectAsync(connectionString).spread(function(client, done) { client.close = done; return client; }); join(fContents, fStat, fSqlClient, function(contents, stat, sqlClient) { var query = " INSERT INTO files (byteSize, contents) VALUES ($1, $2) "; return sqlClient.queryAsync(query, [stat.size, contents]).thenReturn(query); }) .then(function(query) { console.log("Successfully ran the Query: " + query); }) .finally(function() { // This is why you want to use Promise.using for resource management if (fSqlClient.isFulfilled()) { fSqlClient.value().close(); } });
Note: In 1.x and 0.x Promise.join
used to be a Promise.all
that took the values in as arguments instead of an array. This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply
Promise.try
Promise.try(function() fn) -> Promise
Promise.attempt(function() fn) -> Promise
Start the chain of promises with Promise.try
. Any synchronous exceptions will be turned into rejections on the returned promise.
function getUserById(id) { return Promise.try(function() { if (typeof id !== "number") { throw new Error("id must be a number"); } return db.getUserById(id); }); }
Now if someone uses this function, they will catch all errors in their Promise .catch
handlers instead of having to handle both synchronous and asynchronous exception flows.
For compatibility with earlier ECMAScript version, an alias Promise.attempt
is provided for
.Promise.try
Promise.method
Promise.method(function(...arguments) fn) -> function
Returns a new function that wraps the given function fn
. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
This method is convenient when a function can sometimes return synchronously or throw synchronously.
Example without using Promise.method
:
MyClass.prototype.method = function(input) { if (!this.isValid(input)) { return Promise.reject(new TypeError("input is not valid")); } if (this.cache(input)) { return Promise.resolve(this.someCachedValue); } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); };
Using the same function Promise.method
, there is no need to manually wrap direct return or throw values into a promise:
MyClass.prototype.method = Promise.method(function(input) { if (!this.isValid(input)) { throw new TypeError("input is not valid"); } if (this.cache(input)) { return this.someCachedValue; } return db.queryAsync(input).bind(this).then(function(value) { this.someCachedValue = value; return value; }); });
Promise.resolve
Promise.resolve(Promise<any>|any value) -> Promise
Create a promise that is resolved with the given value. If value
is already a trusted Promise
, it is returned as is. If value
is not a thenable, a fulfilled Promise is returned with value
as its fulfillment value. If value
is a thenable (Promise-like object, like those returned by jQuery‘s $.ajax
), returns a trusted Promise that assimilates the state of the thenable.
Example: ($
is jQuery)
Promise.resolve($.get("http://www.google.com")).then(function() { //Returning a thenable from a handler is automatically //cast to a trusted Promise as per Promises/A+ specification return $.post("http://www.yahoo.com"); }).then(function() { }).catch(function(e) { //jQuery doesn‘t throw real errors so use catch-all console.log(e.statusText); });
Promise.reject
Create a promise that is rejected with the given error
.
以上是关于Bluebird-Core API的主要内容,如果未能解决你的问题,请参考以下文章
onActivityResult 未在 Android API 23 的片段上调用
Android 插件化VirtualApp 源码分析 ( 目前的 API 现状 | 安装应用源码分析 | 安装按钮执行的操作 | 返回到 HomeActivity 执行的操作 )(代码片段
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段