<!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的更多相关文章

  1. ES6 Generator vs ES6 async/await

    ES6 Generator vs ES6 async/await next yield promise refs xgqfrms 2012-2020 www.cnblogs.com 发布文章使用:只允 ...

  2. JS学习- ES6 async await使用

    async 函数是什么?一句话,它就是 Generator 函数的语法糖. 使用场景常常会遇到,请求完一个接口,拿完值再去请求另外一个接口,我们之前回调callback函数处理,如果很多的情况下,看起 ...

  3. async包 ES6 async/await的区别

    最基本的async 包 ApCollection.find({}).toArray(function (err, aps) { var num = 0; async.whilst( function ...

  4. ES6 async await 面试题

    转自:https://juejin.im/post/5c0397186fb9a049b5068e54 1.题目一 async function async1(){ console.log('async ...

  5. javascript ES6 新特性之 Promise,ES7 async / await

    es6 一经推出,Promise 就一直被大家所关注.那么,为什么 Promise 会被大家这样关注呢?答案很简单,Promise 优化了回调函数的用法,让原本需要纵向一层一层嵌套的回调函数实现了横向 ...

  6. 使用ES6新特性async await进行异步处理

    我们往往在项目中会遇到这样的业务需求,就是首先先进行一个ajax请求,然后再进行下一个ajax请求,而下一个请求需要使用上一个请求得到的数据,请求少了还好说,如果多了,就要一层一层的嵌套,就好像有点c ...

  7. ES6入门十一:Generator生成器、async+await、Promisify

    生成器的基本使用 生成器 + Promise async+await Promise化之Promisify工具方法 一.生成器的基本使用 在介绍生成器的使用之前,可以简单理解生成器实质上生成的就是一个 ...

  8. (译文)学习ES6非常棒的特性——Async / Await函数

    try/catch 在使用Async/Await前,我们可能这样写: const main = (paramsA, paramsB, paramsC, done) => { funcA(para ...

  9. es6 async和await

    es7 async和await ,作为genertor函数语法糖,在使用上比generator函数方便的,Generator 函数就是一个封装的异步任务,或者说是异步任务的容器.异步操作需要暂停的地方 ...

随机推荐

  1. hello2详解

    1.GreetingServlet.java(显示问候页面表单) 此servlet重写该doGet方法,实现GETHTTP方法.servlet显示一个简单的HTML问候表单,其提交按钮就像hello1 ...

  2. mysql无法连接Can't create a new thread (errno 11)

    问题描述: 今天本地navicat连接服务器mysql出错 ,提示ERROR 1135: Can't create a new thread (errno 11); if you are not ou ...

  3. HTML表单(form)的“enctype”属性

    Form元素的语法中,EncType表明提交数据的格式 属性值: application/x-www-form-urlencoded:在发送前编码所有字符(默认) multipart/form-dat ...

  4. 采用C/C++语言如何实现复数抽象数据类型Complex

    记录一下! 采用C/C++语言如何实现复数抽象数据类型Complex #include <stdio.h> typedef struct Complex { double e1; // 实 ...

  5. wxpython Menus and toolbars

    Menus and toolbars A common part in a GUI application is a menubar. A menubar consists of objects ca ...

  6. Android 应用开发 之通过AsyncTask与ThreadPool(线程池)两种方式异步加载大量数据的分析与对比--转载

     在加载大量数据的时候,经常会用到异步加载,所谓异步加载,就是把耗时的工作放到子线程里执行,当数据加载完毕的时候再到主线程进行UI刷新.在数据量非常大的情况下,我们通常会使用两种技术来进行异步加载,一 ...

  7. python获取硬件信息模块

    https://github.com/redhat-cip/hardware https://github.com/rdobson/python-hwinfo https://github.com/r ...

  8. 【Spring开发】—— AOP之方法级拦截

    前言: 前面介绍了Spring的核心模块以及相关的依赖注入等概念.这篇讲解一下spring的另一个重点,AOP面向切面编程. 说道AOP不得不提到几个概念: 切面:也就是我们自己的一些业务方法. 通知 ...

  9. [USACO17JAN]Subsequence Reversal

    嘟嘟嘟 这题刚开始是什么思路也没有,关键是不知道怎么解决序列反转的问题. 然后我就想到如果暴力反转一个序列的话,实际上就是不断交换数组中的两个数ai和aj,同时要满足交换的数不能交叉. 然后又看了一眼 ...

  10. nodejs protobuff node-protobuf c++ windows扩展安装笔记

    https://www.npmjs.com/package/node-protobuf 按照作者所说的办法在windows平台安装的办法,先到google的github下载2.6.1版本的protob ...