是什么?

https://www.promisejs.org/

What is a promise?

The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:

  • pending - The initial state of a promise.
  • fulfilled - The state of a promise representing a successful operation.
  • rejected - The state of a promise representing a failed operation.

Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).

promise的核心思想是, promise可以表示异步操作的的结果。 包括三个状态, pending, fulfiled, rejected

promise 在英文中是诺言, fulfil promise 为实现诺言,  rejected promise 为 收回诺言。 分别表示成功和失败。

用promise 来描述异步操作结果, 是太形象了, 在当下定义了一个 promise, 诺言的结果, 需要在将来来验证, 不影响当下的运行计划,

例如, 你对你老婆说, 你将来一定要买个大房子给你老婆住。  在你说的时候, 不影响你当天或者明天的工作和生活计划, 该编码就编码, 该散步就散步,

至于以后能不能买到大房子, 那是以后的事情了, 当然诺言要有个期限, 期限已到, 按照诺言, 需要买房, 如果能买到则 fulfill promise, 如果未实现,则reject promise。

如下面例子:

定义了一个读取文件的 promise, 读取成功了调用  fulfill回调, 读取失败了 调用 reject回调。

function readFile(filename, enc){
return new Promise(function (fulfill, reject){
fs.readFile(filename, enc, function (err, res){
if (err) reject(err);
else fulfill(res);
});
});
}

为什么?

如果没有promise, 则例如上例中, 异步读取动作, 我们需要在我们的回调函数callback中, 处理各种错误情况, 和成功情况。

错误情况, 包括:

1、 读取文件失败

2、 解析读取数据失败

成功情况:

1、 解析读取数据成功

使用promise后, 对于成功的情况, 定义成功的处理函数, 对于失败的情况, 定义失败的处理函数。  代码逻辑异常清晰。

function readJSON(filename, callback){
fs.readFile(filename, 'utf8', function (err, res){
if (err) return callback(err);
try {
res = JSON.parse(res);
} catch (ex) {
return callback(ex);
}
callback(null, res);
});
}

怎么用?

除了第一节中,  构造一个promise的例子, 指出要指定 fulfill 和 reject 回调函数, 如果在异步操作完成后, 想做一些其他动作, 则可以调用如下接口,进行定义:

use .then whenever you're going to do something with the result (even if that's just waiting for it to finish)

use .done whenever you aren't planning on doing anything with the result.

function readJSON(filename){
return readFile(filename, 'utf8').then(function (res){
return JSON.parse(res)
})
}

结合 then 和 catch接口, 实现的例子:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

var p1 = new Promise(function(resolve, reject) {
resolve("成功");
}); p1.then(function(value) {
console.log(value); // "成功!"
throw "哦,不!";
}).catch(function(e) {
console.log(e); // "哦,不!"
});

jquery ajax实现

https://api.jquery.com/jQuery.ajax/#jqXHR

$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});

API

  • jqXHR.done(function( data, textStatus, jqXHR ) {});

    An alternative construct to the success callback option, refer to deferred.done() for implementation details.

  • jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

    An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

  • jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });

    An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

    In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

  • jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

    Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Promise API标准

https://www.promisejs.org/api/

每个API都有简单的使用介绍, 很是浅显易懂, i like it。

var p1 = new Promise(function(resolve, reject) {
resolve("Success");
}); p1.then(function(value) {
console.log(value); // "Success!"
throw "oh, no!";
}).catch(function(e) {
console.log(e); // "oh, no!"
}); setTimeout(function(){ p1.then(function(value) {
console.log(value); // "Success!"
throw "oh, no!";
}).then(undefined, function(e) {
console.log(e); // "oh, no!"
}); }, 2000)

Javascript Promise入门的更多相关文章

  1. javaScript Promise 入门

    Promise是JavaScript的异步编程模式,为繁重的异步回调带来了福音. 一直以来,JavaScript处理异步都是以callback的方式,假设需要进行一个异步队列,执行起来如下: anim ...

  2. JavaScript Promise:去而复返

    原文:http://www.html5rocks.com/en/tutorials/es6/promises/ 作者:Jake Archibald 翻译:Amio 女士们先生们,请准备好迎接 Web ...

  3. JavaScript从入门到精通(转)

    JavaScript从入门到精通 转自: https://github.com/Eished/JavaScript_notes 视频连接:https://www.bilibili.com/video/ ...

  4. Promise入门到精通(初级篇)-附代码详细讲解

    Promise入门到精通(初级篇)-附代码详细讲解 ​     Promise,中文翻译为承诺,约定,契约,从字面意思来看,这应该是类似某种协议,规定了什么事件发生的条件和触发方法. ​     Pr ...

  5. promise入门基本使用

    Promise入门详解和基本用法   异步调用 异步 JavaScript的执行环境是单线程. 所谓单线程,是指JS引擎中负责解释和执行JavaScript代码的线程只有一个,也就是一次只能完成一项任 ...

  6. 【转】HTML, CSS和Javascript调试入门

    转 http://www.cnblogs.com/PurpleTide/archive/2011/11/25/2262269.html HTML, CSS和Javascript调试入门 本文介绍一些入 ...

  7. [Javascript] Promise

    Promise 代表着一个异步操作,这个异步操作现在尚未完成,但在将来某刻会被完成. Promise 有三种状态 pending : 初始的状态,尚未知道结果 fulfilled : 代表操作成功 r ...

  8. Javascript Promise 学习笔记

    1.     定义:Promise是抽象异步处理对象以及对其进行各种操作的组件,它把异步处理对象和异步处理规则采用统一的接口进行规范化. 2.     ES6 Promises 标准中定义的API: ...

  9. JavaScript快速入门(四)——JavaScript函数

    函数声明 之前说的三种函数声明中(参见JavaScript快速入门(二)——JavaScript变量),使用Function构造函数的声明方法比较少见,我们暂时不提.function func() { ...

随机推荐

  1. 单色半透明-兼容IE7

    background: #000; width: 100%;height: 100%; filter: alpha(opacity=30); opacity: 0.3;

  2. dedecms为什么文档标题最大长度只能显示二十个汉字呢?

    今天遇到文章标题无论怎么修改,超出二十个汉字不能全部保存,系统只截取前二十个汉字的内容进行保存. 在后台查看系统设置: 系统——其它选项——文档标题最大长度,的值是60,对应的数据库表字段char的长 ...

  3. 手动编译安装docker环境,以及偶尔出现的bug

    总结安装过程如下: 前提:安装git,go,make, docker(docker中编译docker) git clone https://git@github.com/docker/docker c ...

  4. Hibernate的实体类为什么要实现Serializable序列化接口?

    Hibernate的实体类中为什么要继承Serializable?   hibernate有二级缓存,缓存会将对象写进硬盘,就必须序列化,以及兼容对象在网络中的传输 等等. java中常见的几个类(如 ...

  5. 数据分析之pandas入门

    一.数据结构 1. Series 1.1 序列构造和调用 Series是一种类似于一维数组的对象,它由一组数据和索引共同组成,可以通过索引的方式来选取Series中的单个或一组值,常用的构造函数为ob ...

  6. IOS网络第四天 -网络文件上传(0923略)

    01-NSURLSession02-断点续传 02-文件上传01-基本的上传 03-文件上传03-代码封装 04-文件上传04-获得MIMEType.mp4 05-文件的压缩和解压缩.mp4 06-压 ...

  7. JDK环境变量设置

    1,新建JAVA_HOME变量 .  E:\TOOLS\JAVA\JDK1.8.0_111 2,新建CLASSPATH变量 . .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\to ...

  8. Maven项目WEB-INF/views无法引入js,css静态文件解决方法

    web.xml针对文件后缀配置以下,对客户端请求的静态资源如图片.JS文件等的请求交由默认的servlet进行处理 <servlet-mapping> <servlet-name&g ...

  9. java 4种方式读取配置文件 + 修改配置文件

    版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 方式一采用ServletContext读取读取配置文件的realpath然后通过文件流读取出来 方式二采用ResourceB ...

  10. js获取上传文件个数 以及名称

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...