<!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. git每次提交都输入密码

    打开gitbash执行即可 git config --global credential.helper store 长期储存密码,因为git默认是不储存密码的,不执行这条命令的话每次更新代码,或者提交 ...

  2. 2.C#编程语言

    C#(sharp):是一种编程语言,可以开发基于.net平台的应用.   java即是一种平台,也是一名语言.   在.net平台当中,C#是主流语言.C#语言开发的应用不能脱离.net环境而独立运行 ...

  3. WPF - MVVM 之TreeView

    在项目中使用OnPropertyChanged方法,最简单的实例: private event PropertyChangedEventHandler PropertyChanged; protect ...

  4. WPF-MVVM学习心德(WinForm转WPF心德)

    接触MVVM接近一段时间了,有一点理解,写下来. 之前是做winform的,工作需要,学习wpf.优缺点就不用说类,网上一大堆.我自己理解的话,有下面几点: 1.首先是界面的xmal和界面分离:wpf ...

  5. 纯代码编写的vc跳转SB

    今天遇到个问题,我整个项目都是纯代码,突然有个引用的VC用了storyboard,导航的跳转不知道如何操作,最后试了很多方法总算可以了 首先,找到要跳转的sb. UIStoryboard *story ...

  6. NIOSocket Server Client

    最近在看Netty框架,顺便写了一下NIO SocketChannel服务端和客户端 Server.java import java.io.IOException; import java.net.I ...

  7. scss-#{}插值

    一般我们定义的变量都为属性值,可直接使用,但是如果变量作为属性或在某些特殊情况下则必须要以 #{$variables} 形式使用. 例如:scss代码 $borderDirection: top !d ...

  8. 最新机动车行驶证模板PSD可编辑分层文件下载

    机动车行驶证PSD模板下载地址: http://www.qijieworld.com/thread-1834752-1-1.html 模板为psd格式,内容可编辑修改,需使用 Photoshop CS ...

  9. Git回退到指定节点的版本

    1.获取某个历史版本的id(即change-id,每个版本唯一) 方法1:使用git log命令查看所有的历史版本,输入q便可退出. git log 方法2:使用gitk图形化界面查看节点信息.(在安 ...

  10. JSP初学者5

    JSP中include指令和include动作的区别 include指令是编译阶段的指令,即include所包含的文件的内容是编译的时候插入到JSP文件中,  JSP引擎在判断JSP页面未被修改,否则 ...