ES6 async await
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>async-await</title>
</head>
<body>
<h3>ES6 async 函数用法</h3> <script> window.onload = function() { // 例-1: 继发异步
async function f() {
try {
let a = await new Promise((resolve, reject) => {setTimeout(resolve.bind(null, 'hello'), 1000)});
console.log('a: ', a);
let b = await new Promise((resolve, reject) => {setTimeout(resolve.bind(null, 'world'), 2000)});
console.log('b: ', b);
let c = await new Promise((resolve, reject) => {setTimeout(resolve.bind(null, 'xyz'), 3000)});
console.log('c: ', c);
return c;
} catch(error) {
console.log('error: ', error);
}
}
// 继发调用: 回调嵌套, 抛出最后结果, f() 只用来作为一个流程管理器
// f().then(v => {console.log('final-result: '+ v);}).catch(e => {console.log('final-error-reason: ', e);}); // 例-2: 并发异步
async function g() {
try {
return await Promise.all([
ajax1('https://api.github.com/users/github', 'get'),
ajax2('https://api.github.com/users', 'get'),
ajax3('https://api.github.com', 'get'),
ajax4('https://api.github.com/users/chosen', 'get')
]);
} catch(error) {
console.log('error: ', error);
}
} /*
* https://api.github.com/users/github
* https://api.github.com/users
* https://api.github.com
* https://api.github.com/users/chosen
*/ // 并发调用: 全部执行完才抛出最后结果, g() 只用来作为一个流程管理器
g().then(obj => {
let[github, users, api, chosen] = obj; // 解构
let [jGithub, jUsers, jApi, jChosen] = [JSON.parse(github), JSON.parse(users), JSON.parse(api), JSON.parse(chosen)]; // 解构转成 js 对象
// 业务流程
console.log('---------- all-completed ----------');
console.log('github >>>>>>', jGithub['login']);
console.log('users >>>>>>', jUsers[0]['login']);
console.log('api >>>>>>', jApi['current_user_url']);
console.log('chosen >>>>>>', jChosen['login']);
}).catch(e => {
console.log(e);
}) } // --------------- function -------------------- // ajax1
function ajax1(url, type) {
return new Promise((resolve, reject) => {
console.log('ajax1 start~');
myAjax(url, type, null, function(data) {
console.log('ajax1-completed!');
resolve(data);
}, function(reason) {
console.log('ajax1-failed!');
reject(reason);
})
})
} // ajax2
function ajax2(url, type) {
return new Promise((resolve, reject) => {
console.log('ajax2 start~');
myAjax(url, type, null, function(data) {
console.log('ajax2-completed!');
resolve(data);
}, function(reason) {
console.log('ajax2-failed!');
reject(reason);
})
})
} // ajax3
function ajax3(url, type) {
return new Promise((resolve, reject) => {
console.log('ajax3 start~');
myAjax(url, type, null, function(data) {
console.log('ajax3-completed!');
resolve(data);
}, function(reason) {
console.log('ajax3-failed!');
reject(reason);
})
})
} // ajax4
function ajax4(url, type) {
return new Promise((resolve, reject) => {
console.log('ajax4 start~');
console.log('---------- cut-off-line ----------');
myAjax(url, type, null, function(data) {
console.log('ajax4-completed!');
resolve(data);
}, function(reason) {
console.log('ajax4-failed!');
reject(reason);
})
})
}
// 以上 4 个函数(ajax1 ~ ajax4)可以进一步封装, 但为了表达清晰, 此处不做处理 // 自定义 ajax, 类型仅限于 get 和 post, 回调函数: success/error
function myAjax(url, type, params, success, error) {
var xhr = null;
var args = null;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
success(xhr.responseText);
} else {
error("Request was unsuccessful: "+ xhr.status);
}
}
};
xhr.open(type, url, true); // 类型, 连接, 是否异步
if (type.toLowerCase() == 'post') {
// xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 默认的表单提交
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8"); // JSON.stringify 处理后的json 键值对
args = params;
}
xhr.send(args);
}
</script>
</body>
</html>
ES6 async await的更多相关文章
- ES6 Generator vs ES6 async/await
ES6 Generator vs ES6 async/await next yield promise refs xgqfrms 2012-2020 www.cnblogs.com 发布文章使用:只允 ...
- JS学习- ES6 async await使用
async 函数是什么?一句话,它就是 Generator 函数的语法糖. 使用场景常常会遇到,请求完一个接口,拿完值再去请求另外一个接口,我们之前回调callback函数处理,如果很多的情况下,看起 ...
- async包 ES6 async/await的区别
最基本的async 包 ApCollection.find({}).toArray(function (err, aps) { var num = 0; async.whilst( function ...
- ES6 async await 面试题
转自:https://juejin.im/post/5c0397186fb9a049b5068e54 1.题目一 async function async1(){ console.log('async ...
- javascript ES6 新特性之 Promise,ES7 async / await
es6 一经推出,Promise 就一直被大家所关注.那么,为什么 Promise 会被大家这样关注呢?答案很简单,Promise 优化了回调函数的用法,让原本需要纵向一层一层嵌套的回调函数实现了横向 ...
- 使用ES6新特性async await进行异步处理
我们往往在项目中会遇到这样的业务需求,就是首先先进行一个ajax请求,然后再进行下一个ajax请求,而下一个请求需要使用上一个请求得到的数据,请求少了还好说,如果多了,就要一层一层的嵌套,就好像有点c ...
- ES6入门十一:Generator生成器、async+await、Promisify
生成器的基本使用 生成器 + Promise async+await Promise化之Promisify工具方法 一.生成器的基本使用 在介绍生成器的使用之前,可以简单理解生成器实质上生成的就是一个 ...
- (译文)学习ES6非常棒的特性——Async / Await函数
try/catch 在使用Async/Await前,我们可能这样写: const main = (paramsA, paramsB, paramsC, done) => { funcA(para ...
- es6 async和await
es7 async和await ,作为genertor函数语法糖,在使用上比generator函数方便的,Generator 函数就是一个封装的异步任务,或者说是异步任务的容器.异步操作需要暂停的地方 ...
随机推荐
- node.js发邮件
在node上使用第三方类库(nodemailer)发邮件是一件很esay的事情:) app.js 以QQ邮箱为例 var nodemailer = require('nodemailer'); v ...
- Ling之select
select用法: 1.Dictionary<string, string>转json Newtonsoft.Json.JsonConvert.SerializeObject(dicSub ...
- CSP学习之CryptoAPI初识
Crypto API目的就是提供开发者在windows下使用PKI的编程接口. Crypto 提供了很多的加解密相关函数,如编码.解码.加密解密,哈希,数字证书.证书管理证书存储等. 有关 ...
- ireport 导出excel 分页 和 文本转数字格式的解决方法
景:ireport 画excel 报表,导出时要求 数据分页,每页包含 标题和页脚 1.画excel 2.处理分页 首先建立一个变量totalNum 用于记录总共有多少条记录,注意设置属性为Integ ...
- Cass和ArcGIS交换
南方cass图形为CAD,把CAD图形转换成arcgis没有任何问题,到属性有问题,cass存放数据是放在CAD扩展XDATA中,和 arcgis导入导出CAD标准扩展属性不一样,只能二次开发使用,c ...
- python memory-management
http://deeplearning.net/software/theano/tutorial/python-memory-management.html
- 基于VB语言对SolidWorks参数化设计的二次开发
0 引言 随着数字信息化进程的快速推进,如今三维CAD技术在越来越多的企业当中得到运用.为了降低在设计生产中的成本,缩短设计周期,增强企业竞争力,三维参数化技术随之应声,它凭借更贴近现代概念的设计以及 ...
- SQL Server ->> 字符串对比
今天同事问我关于SQL Server在字符串尾随着空格时进行字符串对比的做法.关于这个问题正好在这里讲一下,就是SQL Server是按照ANSI/ISO SQL-92中的定义做字符串对比的. 在KB ...
- Spyder更改默认工作路径已经文件路径
打开spyder,选择菜单栏中的Tools--->Preferences--->Current working directory 然后选择最下面的单选按钮The following ...
- [转]Linux学习
Linux简介与厂商版本 http://www.cnblogs.com/vamei/archive/2012/09/04/2671103.html Linux开机启动(bootstrap) http: ...