JavaScript中的await/async的作用和用法

所属分类: 网络编程 / JavaScript 阅读数: 715
收藏 0 赞 0 分享

await/async 是 ES7 最重要特性之一,它是目前为止 JS 最佳的异步解决方案了。虽然没有在 ES2016 中录入,但很快就到来,目前已经在 ES-Next Stage 4 阶段

直接上例子,比如我们需要按顺序获取:产品数据=>用户数据=>评论数据

老朋友 Ajax

传统的写法,无需解释

// 获取产品数据
ajax('products.json', (products) => {
console.log('AJAX/products >>>', JSON.parse(products));
// 获取用户数据
ajax('users.json', (users) => {
console.log('AJAX/users >>>', JSON.parse(users));
// 获取评论数据
ajax('products.json', (comments) => {
console.log('AJAX/comments >>>', JSON.parse(comments));
});
});
});

不算新的朋友 Promise

Promise 已经被提及已久了,也是 ES6 的一部分。Promise 能消除 callback hell 带来的厄运金字塔,相比起来代码更清晰了。

// Promise
// 封装 Ajax,返回一个 Promise
function requestP(url) {
return new Promise(function(resolve, reject) {
ajax(url, (response) => {
resolve(JSON.parse(response));
});
});
}
// 获取产品数据
requestP('products.json').then(function(products){
console.log('Promises/products >>>', products);
});
// 获取用户数据
requestP('users.json').then(function(users){
console.log('Promises/users >>>', users);
});
// 获取评论数据
requestP('comments.json').then(function(comments){
console.log('Promises/comments >>>', comments);
});

当然使用Promise.all 可以更简洁

Promise.all([
requestP('products.json'),
requestP('users.json'),
requestP('comments.json')
])
.then(function(data) {
console.log('Parallel promises >>>', data);
});

强劲的新朋友 Generators

Generators 也是 ES6 一个新的特性,能够 暂停/执行 代码。yield 表示暂停,iterator.next 表示执行下一步,如果你不了解 Generators 也没关系,可以忽略它直接学习 await/async。

// Generators
function request(url) {
ajax(url, (response) => {
iterator.next(JSON.parse(response));
});
}
function *main() {
// 获取产品数据
let data = yield request('products.json');
// 获取用户数据
let users = yield request('users.json');
// 获取评论数据
let products = yield request('comments.json');
console.log('Generator/products >>>', products);
console.log('Generator/users >>>', users);
console.log('Generator/comments >>>', comments);
}
var iterator = main();
iterator.next(); 

碉堡的朋友 await/async

与 Promise 结合使用

// 封装 Ajax,返回一个 Promise
function requestP(url) {
return new Promise(function(resolve, reject) {
ajax(url, (response) => {
resolve(JSON.parse(response));
});
});
}
(async () => {
// 获取产品数据
let data = await requestP('products.json');
// 获取用户数据
let users = await requestP('users.json');
// 获取评论数据
let products = await requestP('comments.json');
console.log('ES7 Async/products >>>', products);
console.log('ES7 Async/users >>>', users);
console.log('ES7 Async/comments >>>', comments);
}());

与 Fetch API 结合使用:

(async () => {
// Async/await using the fetch API
try {
// 获取产品数据
let products = await fetch('products.json');
// Parsing products
let parsedProducts = await products.json();
// 获取用户数据
let users = await fetch('users.json');
// Parsing users
let parsedUsers = await users.json();
// 获取评论数据
let comments = await fetch('comments.json');
// Parsing comments
let parsedComments = await comments.json();
console.log('ES7 Async+fetch/products >>>', parsedProducts);
console.log('ES7 Async+fetch/users >>>', parsedUsers);
console.log('ES7 Async+fetch/comments >>>', parsedComments);
} catch (error) {
console.log(error);
}
}());

按数组顺序执行

(async () => {
let parallelData = await* [
requestP('products.json'),
requestP('users.json'),
requestP('comments.json')
];
console.log('Async parallel >>>', parallelData);
}());

再次结合 Fetch

(async () => {
let parallelDataFetch = await* [
(await fetch('products.json')).json(),
(await fetch('users.json')).json(),
(await fetch('comments.json')).json()
];
console.log('Async parallel+fetch >>>', parallelDataFetch);
}());

使用 await/async 用同步的思维去解决异步的代码,感觉非常酷非常爽!关于js中的await/async的作用和用法就给大家介绍这么多,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

更多精彩内容其他人还在看

Canvas实现放射线动画效果

本文主要分享了Canvas实现放射线动画的示例代码。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

微信小程序 image组件binderror使用例子与js中的onerror区别

这篇文章主要介绍了微信小程序 image组件binderror使用例子与js中的onerror区别的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

原生js轮播(仿慕课网)

本文主要分享了原生js实现仿慕课网的轮播效果。具有很好的参考价值,下面跟着小编一起来看下吧
收藏 0 赞 0 分享

Bootstrap table简单使用总结

这篇文章主要为大家总结了Bootstrap table的简单使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

微信小程序之MaterialDesign--input组件详解

本篇文章主要介绍了微信小程序之MaterialDesign--input组件详解,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析javaScript中的浅拷贝和深拷贝

本篇文章主要介绍了浅析javaScript中的浅拷贝和深拷贝,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

js时间戳和c#时间戳互转方法(推荐)

下面小编就为大家带来一篇js时间戳和c#时间戳互转方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Bootstrap模态框使用详解

这篇文章主要为大家详细介绍了Bootstrap模态框的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Jil,高效的json序列化和反序列化库

下面小编就为大家带来一篇Jil,高效的json序列化和反序列化库。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

BootStrap实现带关闭按钮功能

这篇文章主要介绍了BootStrap实现带关闭按钮功能,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多