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. emacs 快捷键笔记

    C-d C-aM-aC-eM-e===复制黏贴M-d    kill-wordM-del     backward-kill-wordM-k     kill-sentenceC-x del back ...

  2. 适用于Firemonkey的Json解析对象XsuperObject使用方法介绍

    XSuperObject是适用于FileMonkey平台的JSON解析组件,能够在Android,IOS,MACOS,WINDOWS等多个平台使用 点击下载 Sample JSON { "n ...

  3. res里面的drawable(ldpi、mdpi、hdpi、xhdpi、xxhdpi)

    (1)drawable-hdpi里面存放高分辨率的图片,如WVGA (480x800),FWVGA (480x854) (2)drawable-mdpi里面存放中等分辨率的图片,如HVGA (320x ...

  4. Bundle对象的使用

    在Android开发中,如果要通过一个Activity启动另外一个Activity,需要调用startActivity()函数,这个函数的参数是一个Intent对象,这个对象通常的初始化方式如下: I ...

  5. 如何向hadoop集群定时提交一个jar作业?

    除了使用Hive,Pig来执行一个MapReduce任务,不需要专门的把项目打成jar包,提交执行,或者定时执行,因为Hive,Pig这些开源框架已经,帮我们自动打包上传了. 而有些时候,我们自己手写 ...

  6. OC 设计模式——单例模式

    单例模式的作用:可以保证在程序运行过程,一个类只有一个实例,而且这个实例易于供外界访问.永远只分配一次内存给这个类.由于在调用alloc方法的时候,都会调用allocWithZone,所以要重写这个方 ...

  7. BZOJ 1827 奶牛大集会

    树型DP. #include<iostream> #include<cstdio> #include<cstring> #include<algorithm& ...

  8. 打印Dom对象的所有属性和方法

    <html> <head> <title>Test</title> <meta http-equiv="Content-Type&quo ...

  9. 使用 Linux 终端 SSH 登录 VPS

    Windows 中远程 SSH 登录 VPS 进行管理的利器是 PuTTY,但是 Linux 中就没必要用它了.Linux.Unix(包括 Mac iOS)都必然有内置的命令行终端,内建了 OpenS ...

  10. 【转】【iOS系列】-iOS查看沙盒文件图文教程(真机+模拟器)

    原文网址:http://www.cnblogs.com/fengtengfei/p/5090276.html 1:模拟器 1.1 方法1: 程序中打印一下的地址,能直接前往沙盒路径. NSString ...