请求数据
asyc是:基于promise对象的,返回的是一个promise对象,asyc是一个关键字;’
await是请求数据:可以取代ajax,目前ajax可以使用;
Fetch也是可以完成的,和promise进行嵌套更好;**
# 第七章:async & await
基本用法
ES2017 标准引入了 async 函数,使得异步操作变得更加方便。
async 函数是什么?
- async 关键字,用来修饰函数,把这种函数称之为asyn函数
- async 是es8中,引入的,一个用于异步编程的一种解决方案;
- async函数返回一个 Promise 对象,可以使用then方法添加回调函数。
async
函数内部return
语句返回的值,会成为then
方法回调函数的参数
function fn(){}
console.log(fn()); //undefined
async function fn(){}
console.log(fn()); //Promise PromiseState:'fulfilled' PromiseResult:undefined
async function fn(){
return 0;
}
console.log(fn()); //Promise PromiseState:'fulfilled' PromiseResult:0
//async函数返回一个 Promise 对象,可以使用then方法添加回调函数。
fn().then(res=>console.log(res)); //0
await
- await命令与async配合使用,正常情况下,await命令后面是一个 Promise 对象,返回该对象的结果。如果不是 Promise 对象,就直接返回对应的值。
如果函数内使用了await,外层函数必须要用async修饰
async function f2(){
let res = await new Promise((resolve,reject)=>{
if(true){
resolve({msg:'嘿嘿嘿'});
}else{
reject({msg:'error~'});
}
});
console.log(res);
}
f2();//{msg:'嘿嘿嘿'}
async function f3() {
let res = await 123;
console.log('函数内部'+res);
return res;
}
f3().then(res=>{
console.log(res);//函数内部123 123
})
- 当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。
- await 不是同步的,是异步的,遇到await以后,await以后的代码会进入任务队列,当所有的主线程上的同步任务执行完以后,才会执行await;
async function f4(){
console.log(111111);
let r = await 22222;
console.log(r);
console.log(33333);
}
f4();
console.log(444444);
- await 命令必须写在async函数中,否则语法错误
async
函数返回一个 Promise 对象。
async
函数内部return
语句返回的值,会成为then
方法回调函数的参数。
async
函数返回的是一个prmise对象,但是并不是说async函数内部必须要写promise代码
async function f() {
return 'hello world';
}
f().then(v => console.log(v))
// "hello world"
上面代码中,函数f
内部return
命令返回的值,会被then
方法回调函数接收到。
async
函数内部抛出错误,会导致返回的 Promise 对象变为reject
状态。抛出的错误对象会被catch
方法回调函数接收到。
async function f() {
throw new Error('出错了');
}
f().then(
v => console.log('resolve', v),
e => console.log('reject', e)
)
//reject Error: 出错了
async 函数有多种使用形式。
// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = {
fn:function(){},
//等价
fn(){},
async demo(){},
async foo() {}
};
obj.foo().then(...)
// Class 的方法
class Storage {
constructor() {
this.cachePromise = caches.open('avatars');
}
async getAvatar(name) {
const cache = await this.cachePromise;
return cache.match(`/avatars/${name}.jpg`);
}
}
const storage = new Storage();
storage.getAvatar('jake').then(…);
// 箭头函数
const foo = async () => {};
Fetch API
- fetch 基于promise
- 默认是get 方式
- 提供了一个全局 fetch() 方法,该方法提供了一种简单,合理的方式来跨网络异步获取资源。 这种功能以前是使用 XMLHttpRequest 实现的。Fetch 提供了一个更理想的替代方案
fetch('http://localhost:4000?name=三体').then(res=>{
// 返回的是服务端的响应。不是真正的数据;
// 但是,我们要获取数据,就要 使用一个方法res.json();
// console.log(res);
return res.json();
}).then(res=>{
console.log(res);
let { data: [{author}]} = res;
return fetch(`http://localhost:4000?author=${author}`);
}).then(res=>{
return res.json();
}).then(res=>{
console.log(res);
});
//fetch 与 async 结合使用await
async function fn() {
let res = await fetch('http://localhost:4000?name=三体');
res = await res.json();
let {data: [{author}]} = res;
let r = await fetch(`http://localhost:4000?author=${author}`);
return await r.json();
}
fn().then(res => console.log(res));