【译】JavaScript Promise API
在 JavaScript 中,同步的代码更容易书写和 debug,但是有时候出于性能考虑,我们会写一些异步的代码(代替同步代码)。思考这样一个场景,同时触发几个异步请求,当所有请求到位时我们需要触发一个回调,怎么做?Promise 让一切变的简单,越来越多的原生 API 基于 Promise 去实现。那么,什么是 Promise?Promise API 如何使用?
基于 Promise 的 原生 API
Promise 主要是为了解决异步的回调地狱。我们熟悉的 XMLHttpRequest API 可以异步使用,但是它没有基于 Promise API。一些原生的 API 已经使用了 Promise,比如:
- Battery API
- fetch API(下一代 XHR)
- ServiceWorker API
对于 Promise 的测试其实非常简单,使用 SetTimeout 就能当做一个异步的事件来测试。
Promise 基本用法
Promise 本质其实是一个构造函数,其接受一个函数作为参数,而这个函数内部一般会写一些异步事件处理的代码,比如 SetTimeout 或者 XMLHttpRequest。异步事件我们一般都会有一个 "失败" 的处理机制,我们还可以给这个作为参数的函数传入两个参数 resolve 和 reject,分别表示异步事件 "成功" 和 "失败" 时的回调函数。
let p = new Promise((resolve, reject) => {
// Do an async task
setTimeout(() => {
// good condition
if (Math.random() > 0.5) {
resolve('The number is bigger than 0.5');
} else {
reject('The number is smaller than 0.5');
}
}, 1000);
});
p.then(data => {
// do something with the result
console.log(data);
}, data => {
// do something with the result
console.log(data);
});
对于什么时候调用 resolve(可以粗略理解为异步操作成功)或者 reject(可以粗略理解为异步操作失败)作为异步事件的回调函数,完全取决于开发者。
以下的代码我们将 XMLHttpRequest 基于 Promise 去实现:
// From Jake Archibald's Promises and Back:
// http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promisifying-xmlhttprequest
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
// Use it!
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.error("Failed!", error);
});
Promise 构造函数调用 new 操作符,传入一些异步事件的代码,会生成一个 Promise 实例对象,但是有的时候,我们需要生成一个 Promise 的实例对象,但是并不需要执行一些异步代码,我们可以用 Promise.resolve() 和 Promise().reject() 来做这件事情。
var userCache = {};
function getUserDetail(username) {
// In both cases, cached or not, a promise will be returned
if (userCache[username]) {
// Return a promise without the "new" keyword
return Promise.resolve(userCache[username]);
}
// Use the fetch API to get the information
// fetch returns a promise
return fetch('users/' + username + '.json')
.then(function(result) {
userCache[username] = result;
return result;
})
.catch(function() {
throw new Error('Could not find user: ' + username);
});
}
getUserDetail() 会始终返回一个 Promise 实例,所以 then 等方法可以在该函数返回值(即 Promise 实例)中使用。
then
所有 Promise 实例均拥有 then 方法,then 方法上可以定义两个回调函数,第一个回调函数能接收到实例化 Promise 时通过 resolve 方法传递过来的参数(必须),而第二个回调函数对应 reject 方法(可选)。
new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve(10); }, 1000);
})
.then(function(result) {
console.log(result);
});
// From the console:
// 10
当这个 Promise 实例内部调用 resolve 方法时(Pending -> Resolved),then 中的第一个参数代表的回调函数被触发。
then 也能被链式调用。
new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve(10); }, 3000);
})
.then(function(num) { console.log('first then: ', num); return num * 2; })
.then(function(num) { console.log('second then: ', num); return num * 2; })
.then(function(num) { console.log('last then: ', num);});
// From the console:
// first then: 10
// second then: 20
// last then: 40
在 then 方法中,可以直接 return 数据而不是 Promise 对象,在后面的 then 中就可以接受到数据了。
catch
catch 方法有两个作用。
第一个作用可以代替 then 方法的第二个参数。
let p = new Promise((resolve, reject) => {
// Do an async task
setTimeout(() => {
// good condition
if (Math.random() > 0.5) {
resolve('The number is bigger than 0.5');
} else {
reject('The number is smaller than 0.5');
}
}, 1000);
});
p.then(data => {
// do something with the result
console.log(data);
}).catch(data => {
// replace the second argument of then function
console.log(data);
});
第二个作用有点像 try-catch,尝试捕获错误。在执行 resolve 的回调(也就是 then 中的第一个参数)时,如果抛出异常了(代码出错),那么会进入这个 catch 方法中。
let p = new Promise((resolve, reject) => {
// Do an async task
setTimeout(() => {
// good condition
if (Math.random() > 0) {
resolve('The number is bigger than 0');
}
}, 1000);
});
p.then(data => {
// do something with the result
console.log(data);
throw new Error();
}).catch(error => {
console.log('There is an error.');
});
// The number is bigger than 0
// There is an error.
Promise.all
回到本文开头说的应用场景,如果多个异步事件同时请求,我们需要在所有事件完成后触发回调,Promise.all 方法可以满足。该方法接收一个 Promise 实例组成的数组作为参数,当该数组中的所有 Promise 实例的状态变为 resolved 时,触发回调方法,回调方法的参数是由所有 Promise 实例的 resolve 函数的参数组成的数组。
Promise.all([promise1, promise2]).then(function(results) {
// Both promises resolved
})
.catch(function(error) {
// One or more promises was rejected
});
Promise.all 可以和 fetch 结合使用,因为 fetch 方法始终返回 Promise 实例。
var request1 = fetch('/users.json');
var request2 = fetch('/articles.json');
Promise.all([request1, request2]).then(function(results) {
// Both promises done!
});
有任意的 Promise 实例抛出异常就会进入 catch 方法,但是需要注意的是,异步事件并不会停止执行。
var req1 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() {
resolve('First!');
console.log('req1 ends!');
}, 4000);
});
var req2 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.all([req1, req2]).then(function(results) {
console.log('Then: ', results);
}).catch(function(err) {
console.log('Catch: ', err);
});
// From the console:
// Catch: Second!
// req1 ends!
Promise.race
Promise.race 接收参数和 Promise.all 类似,但是有任何实例状态变为 resolved 或者 rejected 时,就会调用 then 或者 catch 中的回调。很显然,它的回调的参数是一个值,并不是一个数组。
var req1 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { resolve('First!'); }, 8000);
});
var req2 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.race([req1, req2]).then(function(one) {
console.log('Then: ', one);
}).catch(function(one, two) {
console.log('Catch: ', one);
});
// From the console:
// Then: Second!
对于 Promise.race 方法,需要注意的是,虽然有一个异步事件有了结果,便会执行 then 或者 catch 中的回调,但是其他的异步事件其实还会继续执行。
var req1 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() {
resolve('First!');
console.log('req1 end!');
}, 8000);
});
var req2 = new Promise(function(resolve, reject) {
// A mock async action using setTimeout
setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.race([req1, req2]).then(function(one) {
console.log('Then: ', one);
}).catch(function(one, two) {
console.log('Catch: ', one);
});
// From the console:
// Then: Second!
// req1 end!
有个简单的应用,有个文件的请求我们有多个地址,很显然请求到了任意一个即可。
熟悉 Promise
我们有必要掌握 Promise,Promise 可以有效防止回调地狱,优化异步交互,使得异步代码更加直观。而且越来越多的原生 API 基于 Promise 去实现,我们有必要知其然,知其所以然。
【译】JavaScript Promise API的更多相关文章
- JavaScript Promise API
同步编程通常来说易于调试和维护,然而,异步编程通常能获得更好的性能和更大的灵活性.异步的最大特点是无需等待."Promises"渐渐成为JavaScript里最重要的一部分,大量的 ...
- Javascript Promise入门
是什么? https://www.promisejs.org/ What is a promise? The core idea behind promises is that a promise r ...
- [Javascript] Promise
Promise 代表着一个异步操作,这个异步操作现在尚未完成,但在将来某刻会被完成. Promise 有三种状态 pending : 初始的状态,尚未知道结果 fulfilled : 代表操作成功 r ...
- Javascript Promise 学习笔记
1. 定义:Promise是抽象异步处理对象以及对其进行各种操作的组件,它把异步处理对象和异步处理规则采用统一的接口进行规范化. 2. ES6 Promises 标准中定义的API: ...
- JavaScript Promise:去而复返
原文:http://www.html5rocks.com/en/tutorials/es6/promises/ 作者:Jake Archibald 翻译:Amio 女士们先生们,请准备好迎接 Web ...
- Promise API
Promise API 刚刚接触promise这个东西,网上看了很多博客,大部分是讲怎么用Promise,丝毫没提怎么实现Promise. 我不甘 心,可是真去看JQuery或者Angular ...
- Promise API 简介
Promise API 简介 译者注: 到处是回调函数,代码非常臃肿难看, Promise 主要用来解决这种编程方式, 将某些代码封装于内部. Promise 直译为"承诺",但一 ...
- javascript的api设计原则
前言 本篇博文来自一次公司内部的前端分享,从多个方面讨论了在设计接口时遵循的原则,总共包含了七个大块.系卤煮自己总结的一些经验和教训.本篇博文同时也参考了其他一些文章,相关地址会在后面贴出来.很难做到 ...
- 深入理解javascript选择器API系列第三篇——h5新增的3种selector方法
× 目录 [1]方法 [2]非实时 [3]缺陷 前面的话 尽管DOM作为API已经非常完善了,但是为了实现更多的功能,DOM仍然进行了扩展,其中一个重要的扩展就是对选择器API的扩展.人们对jQuer ...
随机推荐
- windows server 2012 AD 活动目录部署系列(五)备份和还原域控制器
在前篇博文中,我们介绍了用户资源的权限分配,用户只要在登录时输入一次口令,就能访问基于该域所分配给他的所有资源. 但是我们需要考虑一个问题:万一域控制器坏了怎么办?!如果这个域控制器损坏了,那用户登录 ...
- 起步X5 的铛铛的安装部署过程
(2017年1月)主要资料: 1.铛铛的IM Server即时通信服务使用 actor https://github.com/actorapp/actor-platform ,开发者网站是:htt ...
- JS利用短路原理简写if语句
看GoogleDoodle-Dance的源代码,学习到一个小知识——简写if语句. 几乎所有语言中||和&&都遵循“短路”原理,如&&中第一个表达式为假就不会去处理第二 ...
- UIAlertController 自定义输入框及KVO监听
UIAlertController极大的灵活性意味着您不必拘泥于内置样式.以前我们只能在默认视图.文本框视图.密码框视图.登录和密码输入框视图中选择,现在我们可以向对话框中添加任意数目的UITextF ...
- UIAlertController 自定义输入框及KVO监听 分类: ios技术 2015-01-20 15:33 199人阅读 评论(1) 收藏
UIAlertController极大的灵活性意味着您不必拘泥于内置样式.以前我们只能在默认视图.文本框视图.密码框视图.登录和密码输入框视图中选择,现在我们可以向对话框中添加任意数目的UITextF ...
- java web基础 --- URL重定向Filter
java web基础 --- URL重定向Filter httpRequest.getRequestDispatcher("/helloWorld").forward(httpRe ...
- python 错误AttributeError: 'module' object has no attribute 'AF_INET'
写了一个简单的python socket的程序.运行时,报错如下 原因:文件的命名与Python的function的命名冲突 修改名称后,发现还是无法运行,检查目录下面是否有 这样子的一个文件,删除即 ...
- Unity3D ——强大的跨平台3D游戏开发工具(六)
第十一章 制作炮台的旋转 大家知道,炮台需要向四周不同的角度发射炮弹,这就需要我们将炮台设置成为会旋转的物体,接下来我们就一起制作一个会旋转的炮台. 第一步:给炮台的炮筒添加旋转函数. 给炮台的炮筒部 ...
- 从CK+库提取标记点信息
1.CK+动态表情库介绍 The Extended Cohn-Kanade Dataset(CK+) 下载地址 这个数据库是在 Cohn-Kanade Dataset 的基础上扩展来的,发布于2010 ...
- APP IM 之 XMPP和Jabber及选择方案
1. 概述 IM ,InstantMessaging,即时通信. 现在,市面上有一批提供即时通信功能的公司.如:全时.云之讯(IM无语音和视频).容联云通讯(支持点对点音视频,按照消息的存储空间收费) ...