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, .allPromise.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 (三)的更多相关文章
- .NET Core项目部署到Linux(Centos7)(三)创建.NET Core API项目
目录 1.前言 2.环境和软件的准备 3.创建.NET Core API项目 4.VMware Workstation虚拟机及Centos 7安装 5.Centos 7安装.NET Core环境 6. ...
- AspNet Core Api Restful 实现微服务之旅 (一)
(一)了解微服务(二)搭建VS项目框架 (三)创建AspNet Core Api VS2017 安装包 链接:https://pan.baidu.com/s/1hsjGuJq 密码:ug59 创 ...
- 【从零开始搭建自己的.NET Core Api框架】(七)授权认证进阶篇
系列目录 一. 创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...
- 【从零开始搭建自己的.NET Core Api框架】(一)创建项目并集成swagger:1.1 创建
系列目录 一. 创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...
- 【从零开始搭建自己的.NET Core Api框架】(四)实战!带你半个小时实现接口的JWT授权验证
系列目录 一. 创建项目并集成swagger 1.1 创建 1.2 完善 二. 搭建项目整体架构 三. 集成轻量级ORM框架——SqlSugar 3.1 搭建环境 3.2 实战篇:利用SqlSuga ...
- 详解ASP.NET Core API 的Get和Post请求使用方式
上一篇文章帮助大家解决问题不彻底导致博友使用的时候还是遇到一些问题,欢迎一起讨论.所以下面重点详细讲解我们常用的Get和Post请求( 以.net core2.2的Http[Verb]为方向 ,推荐该 ...
- ASP.NET Core API 接收参数去掉烦人的 [FromBody]
在测试ASP.NET Core API 项目的时候,发现后台接口参数为类型对象,对于PostMan和Ajax的Post方法传Json数据都获取不到相应的值,后来在类型参数前面加了一个[FromBody ...
- Express4.x API (三):Response (译)
Express4.x API 译文 系列文章 Express4.x API (一):application (译) -- 完成 Express4.x API (二):request (译) -- 完成 ...
- 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 ...
- 利用BenchmarkDotNet 测试 .Net Core API 同步和异步方法性能
事由: 这两天mentor给我布置了个任务让我用BenchmarkDotNet工具去测试一下同一个API 用同步和异步方法写性能上有什么差别. 顺带提一下: 啊啊啊啊 等我仔细看文档的时候文档 发现它 ...
随机推荐
- [原]Water Water Union-Find Set & Min-Spanning Tree Problems' Set~Orz【updating...】
[HDU] 1213 - How Many Tables [基础并查集,求父节点个数] 1856 -More is better [基础并查集,注意内存,HDU数据水了,不用离散化,注意路径压缩的方式 ...
- YTU 2614: A代码完善--系统日期
2614: A代码完善--系统日期 时间限制: 1 Sec 内存限制: 128 MB 提交: 216 解决: 113 题目描述 注:本题只需要提交填写部分的代码,请按照C++方式提交. 已知某操作 ...
- PHP文件上传代码和逻辑详解
文件上传的逐步完善------ [简单的上传:] <form action="upload.php" method="post" enctype= ...
- 不同浏览器JS获取浏览器高度和宽度
摘自:http://blog.csdn.net/lai_gb/archive/2009/07/04/4320956.aspx IE中: document.body.clientWidth ==> ...
- D3D中深度测试和Alpha混合的关系
我在学习D3D的深度测试和Alpha混合的时候,有一些遗憾.书上提供的例子里说一定要先渲染不透明物体,再渲染透明物体,对渲染状态的设置也有特殊要求.我看的很晕.自己查图形学的书,上网找资料,结果还是糊 ...
- HTML5_拖放
拖放(Drag 和 drop)是 HTML5 标准的组成部分.拖放是一种常见的特性,即抓取对象以后拖到另一个位置.在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放. 支持的浏览器:Inter ...
- Qt之等待提示框(QMovie)
简述 关于gif的使用在实际项目中我用的并不多,因为我感觉瑕疵挺多的,很多时候锯齿比较严重,当然与图存在很大的关系. 关于生成gif的方法可以提供一个网站preloaders,基本是可以满足需求的. ...
- java MVC设计模式
MVC(Model View Control)模型-视图-控制器 一.MVC与模板概念的理解 MVC本来是存在于Desktop程序中的,M是指数据模型,V是指用户界面,C则是控制器.使用MVC的目的是 ...
- BZOJ 1617 渡河问题
普及组dp. #include<iostream> #include<cstdio> #include<cstring> #include<algorithm ...
- ios中get,post和解压缩用法
一. 网络概念 1. 在Linux系统上,运行的Web服务器的名字叫做Apache 2. 所有的http访问都是基于html或者相关的文件,例如:php,asp,jsp,asp.net 这些文件最终都 ...