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. zabbix接口调用注意事项--Python

    不知道该怎么写,但是明显得写点什么,担心时间长了,忘记,再回顾时又要重新摸索一遍 一.Request:post params: 1. 第一层的参数处理: 第一层的参数设置为变量 2. 其他层参数格式不 ...

  2. svn服务器及客户端安装使用

    一.服务器安装: 1.yum install subversion   2.输入rpm -ql subversion查看安装位置,如下图:   我们知道svn在bin目录下生成了几个二进制文件. 输入 ...

  3. 笔记一、Git服务器【转】

    传输协议: 本地传输,SSH协议,Git协议,HTTP协议   git clone /home/git/project.git                      // 本地clone git ...

  4. 《c程序设计语言》读书笔记--大写转小写

    #include <stdio.h> #include <stdlib.h> #include <string.h> int aoti(char c) { if(c ...

  5. 【HDOJ】5446 Unknown Treasure

    1. 题目描述题目很简单,就是求$C(n,m) % M$. 2. 基本思路这是一道应用了众多初等数论定理的题目,因为数据范围较大因此使用Lucas求$C(n,m) % P$.而M较大,因此通过$a[i ...

  6. explicit constructor(显示构造函数)

    按照默认规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应的数据类型的数据转换为该类对象,如下所示: class String { String(const char* p) //用C ...

  7. 瞎折腾之 VS2013 Cordova项目的创建与配置

    扯淡 什么是Cordova ? 网上查询的说明: Cordova是贡献给Apache后的开源项目,是从PhoneGap中抽出的核心代码,是驱动PhoneGap的核心引擎.你可以把他想象成类似于Webk ...

  8. Js内置对象的应用

    Boolean.Number.Objectfunction对象    另一种写法:        var add=new Function("x","y",&q ...

  9. acdream 1683 村民的怪癖(KMP,经典变形)

    Problem Description 娜娜费劲九牛二虎之力终于把糖果吃完了(说好的吃不完呢?骗人,口亨~),于是,缘溪行,忘路之远近.忽逢桃花林,夹岸数百步,中无杂树,芳草鲜美,落英缤纷,娜娜甚异之 ...

  10. 自己构建MVC中的M

    /** * @ description Model MVC中M 数据模型 * @ Object * @ public * @ create method IE不支持 */ if(typeof Obje ...