Fetch and await
来源:互联网 发布:2017淘宝评价记分规则 编辑:程序博客网 时间:2024/06/05 02:35
- 老朋友Ajax
- Promise
- Fetch API
- await
await/async 是 ES7 最重要特性之一,它是目前为止 JS 最佳的异步解决方案了。虽然没有在 ES2016 中录入,但很快就到来,目前已经在 ES-Next Stage 4 阶段。
https://segmentfault.com/a/1190000007116715
直接上例子,比如我们需要按顺序获取:产品数据=>用户数据=>评论数据
老朋友 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((products) => {
console.log(‘Promises/products >>>’, products);
// 获取用户数据
return requestP(‘users.json’);
}).then((users) => {
console.log(‘Promises/users >>>’, users);
// 获取评论数据
return requestP(‘comments.json’);
}).then((comments) => {
console.log(‘Promises/comments >>>’, comments);
});
强劲的新朋友 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);}
}());
再次结合 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 用同步的思维去解决异步的代码,感觉非常酷非常爽!
放在后面:
// jQuery
$.getJSON(‘/users’).then(success, fail)
// Axios
axios.get(‘/users’).then(success, fail);
// Backbone
users.fetch().then(success, fail)
// Fetch (hey, you need to download 4-5kb min+gz of Fetch and Promise polyfills if you have IE<=11 or older mobile browsers)
// There’s actually more request config & response verification that should be done if you want it as robust as the xhr libs
// And you can’t cancel these, but they do stream
fetch(‘/users’, {credentials: ‘same-origin’})
.then(function(response) {
if (response.ok) {
return response.json();
}
else {
// Reject the response since it’s not a 200-level response (i.e. there’s no usable data here)
throw new Error(‘Throw or else you’ll be trying to response.json() on 404s!’);
}
})
.then(success)
.catch(fail);
- Fetch and await
- [c#]: async and await
- async and await 操作实例
- Async and await的使用
- Fetch XML and ConditionExpression operators
- Promise with fetch and post
- Fetch XML and ConditionExpression operators
- async and await 简单的入门
- async and await 简单的入门
- Task and Await: Consuming Awaitable Methods
- async and await 简单的入门
- .NET-Demo for async and await
- Asynchronous Programming with async and await (C#)用async和await实现异步编程
- git: fetch and merge, don’t pull
- Git分支 and Pull&Fetch&Merge
- FETCH
- Fetch
- FETCH
- Innodb锁机制:Next-Key Lock 浅谈
- Git 项目免密拉取代码-自动保存账号密码
- 深度学习哪家强?吴恩达、Udacity和Fast.ai
- 架构漫谈(四):如何做好架构之架构切分
- Vue.js Devtools inspection is not available because it's in production mode or explicitly disabled
- Fetch and await
- vim之spellchecking
- 架构漫谈(三):如何做好架构之识别问题
- ORA-54033 要修改的列由某个虚拟表达式使用
- Intellij IDEA 快捷键整理(TonyCody)
- 你好,旧时光!
- Beyond Compare Pro for Mac 无限试用
- C++中的二等公民
- 基于深度学习的视频检测(三) 目标跟踪