Bluebird-Core API (三)

Promise.join

Promise.join(
    Promise<any>|any values...,
    function handler
) – -> Promise

 

For coordinating multiple concurrent discrete promises. While .all is good for handling a dynamically sized list of uniform promises, 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:password@localhost/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 valueis 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.

posted @ 2016-06-26 16:31  小彭博客  阅读(417)  评论(0编辑  收藏  举报