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.

Bluebird-Core API (三)的更多相关文章

  1. .NET Core项目部署到Linux(Centos7)(三)创建.NET Core API项目

    目录 1.前言 2.环境和软件的准备 3.创建.NET Core API项目 4.VMware Workstation虚拟机及Centos 7安装 5.Centos 7安装.NET Core环境 6. ...

  2. AspNet Core Api Restful 实现微服务之旅 (一)

    (一)了解微服务(二)搭建VS项目框架  (三)创建AspNet Core Api VS2017 安装包   链接:https://pan.baidu.com/s/1hsjGuJq 密码:ug59 创 ...

  3. 【从零开始搭建自己的.NET Core Api框架】(七)授权认证进阶篇

    系列目录 一.  创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...

  4. 【从零开始搭建自己的.NET Core Api框架】(一)创建项目并集成swagger:1.1 创建

    系列目录 一.  创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...

  5. 【从零开始搭建自己的.NET Core Api框架】(四)实战!带你半个小时实现接口的JWT授权验证

    系列目录 一.  创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...

  6. 详解ASP.NET Core API 的Get和Post请求使用方式

    上一篇文章帮助大家解决问题不彻底导致博友使用的时候还是遇到一些问题,欢迎一起讨论.所以下面重点详细讲解我们常用的Get和Post请求( 以.net core2.2的Http[Verb]为方向 ,推荐该 ...

  7. ASP.NET Core API 接收参数去掉烦人的 [FromBody]

    在测试ASP.NET Core API 项目的时候,发现后台接口参数为类型对象,对于PostMan和Ajax的Post方法传Json数据都获取不到相应的值,后来在类型参数前面加了一个[FromBody ...

  8. Express4.x API (三):Response (译)

    Express4.x API 译文 系列文章 Express4.x API (一):application (译) -- 完成 Express4.x API (二):request (译) -- 完成 ...

  9. C#中缓存的使用 ajax请求基于restFul的WebApi(post、get、delete、put) 让 .NET 更方便的导入导出 Excel .net core api +swagger(一个简单的入门demo 使用codefirst+mysql) C# 位运算详解 c# 交错数组 c# 数组协变 C# 添加Excel表单控件(Form Controls) C#串口通信程序

    C#中缓存的使用   缓存的概念及优缺点在这里就不多做介绍,主要介绍一下使用的方法. 1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可:  <%@ Outp ...

  10. 利用BenchmarkDotNet 测试 .Net Core API 同步和异步方法性能

    事由: 这两天mentor给我布置了个任务让我用BenchmarkDotNet工具去测试一下同一个API 用同步和异步方法写性能上有什么差别. 顺带提一下: 啊啊啊啊 等我仔细看文档的时候文档 发现它 ...

随机推荐

  1. Java中什么时候使用构造方法

    JAVA是面向对象的语言,面向对象不是这么直接简单,它的设计思想就是要代码重用.即我以前干过类似的事,那么我找出以前可以用到的代码,完成一部分.以前没有的我重新写.这样就有了类.有了类,就是有了可以重 ...

  2. mongodb unset/set 删除/增加字段

    删除全部文档的name字段 db.users.update({},{$unset: {"name":""}},{nulti:true}) 增加全部文档的name ...

  3. JSON 之 SuperObject(4): 增、删、改

    unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, For ...

  4. R语言AMORE包实现BP神经网络——German数据集

    library(AMORE)data<-read.table('G:\\dataguru\\ML\\ML09\\基于BP网络的个人信贷信用评估\\基于BP网络的个人信贷信用评估\\german. ...

  5. 64位Ubuntu 13.04 安装Bochs 2.3.5

    bochs 2.3.5源码编译 网上编译bochs的资料非常多,基本的问题都有解决方案,我重点讲不常见的问题. 基本安装步骤 tar vxzf bochs-2.3.5.tar.gz cd bochs- ...

  6. 51nod1434 区间LCM

    将n!标准分解.m!/n!必定需要包含n!的分解式.对于每个质数枚举最小的答案,然后总的取最大. #include<cstdio> #include<cstring> #inc ...

  7. BZOJ 3653 谈笑风生

    ORZ blutrex...... 主席树. #include<iostream> #include<cstdio> #include<cstring> #incl ...

  8. 一个基于WebGL的仿真3D水池有逼真的水波纹效果

    最近在研究WebGL,看到国外很多高手做的很多超炫的3D效果,无比羡慕.忍不住把效果趴下来研究,下面介绍一个逼真的游泳池中浮动小球的效果.效果非常绚丽,功能强大.示例可切换观察水池的视角,不同视角考虑 ...

  9. IntelliJ IDEA使用总结篇

    解决控制台中文乱码的问题: 1.windows下改intellij安装目录下bin\idea.exe.vmoptions文件 加上 -Dfile.encoding=UT 2.设置IDEA server ...

  10. 【英语】Bingo口语笔记(67) - turn系列