含义
async函数使异步操作更方便。
它就是Generator的语法糖。(自行了解一下Generator)
async函数返回的是一个Promise对象,可以使用then方法添加回调函数.当函数执行的时候,遇到await,就会先返回,等到异步操作完成后,再去执行函数体内后面的语句。
function timeout(ms){
return new Promise((resolve,reject)=>{
setTimeout(resolve,ms) ;
})
}
async function asyncTime(value,ms){
await timeout(ms);
console.log(value)
}
asyncTime('helloworld',50);
async 有多种使用形式
1函数声明
async function foo(){}
2函数表达式
const foo=async function(){}
3对象的方法
let obj={async foo(){}}
obj.foo.then(...)
4class的方法
class Stronge={
constructor={
this.cachePromise=caches;
}
async getCache(name){
const cache=this.chchePromise();
return cache+name
}
}
let sto=new Stronge();
sto.getCache('xzz').then()
5箭头函数
const foo = async()=>{}
语法 1 返回Promise对象
async 函数 返回一个 Promise对象
async函数内部的return返回的值,会成为then回调的参数
async function foo(){
return 'helloworld'
}
foo().then(c=>{console.log(c)})
async 函数内部抛出错误,会导致返回的Promise状态变成reject,抛出的对象会被catch方法函数回调到。
async function f(){
throw new Error('出错了')
}
f().then(v=>{console.log(v)}) //Error: 出错了
语法 2 Promise对象的状态改变
async 函数返回的Promise对象,必须等到内部await后面的Promise对象执行完,
或者说是遇到return、抛出错误,才会发生状态改变。只有async函数的异步操作完成,才执行then内的函数。
async function getTitle(url){
const reponse=await fetch.get(url); //执行1
const result=await reponse.text(); //执行2
return alert(result); //操作完成
}
getTitle('www.baidu.com').then(v=>{console.log(v)})
语法3 await
await 后面是一个Promise对象,如果不是,会转化为一个Promise对象
async function aa(){
return await 123;
}
aa().then(c=>{console.log(c)})
// 123
// Promise {<resolved>: undefined}
// __proto__: Promise
// [[PromiseStatus]]: "resolved"
// [[PromiseValue]]: undefined
await后面的参数123,被转化为Promise对象,并立即resolve
如果await的Promise对象是reject 状态,那么会被catch接收到
async function foo(){
await Promise.reject('ddd');
}
foo().then().catch(c=>{console.log(c)}) //ddd
只要 await 后面的Promise状态变成reject,其他的就不会执行了
async function foo(){
await Promise.reject('ddd');
await 123;
}
如果第一个是reject,但是还是想要执行第2个,可以把第一个await放在try catch里,不管它成功失败,第二个都会执行
async function foo(){
try{
await Promise.reject('aaa')
}catch(e){}
return await Promise.resolve('123')
}
foo().then(v=>{console.log(v)})
如果有多个await 操作,可以放在try catch里
async function foo(){
try{
const result=await getOne();
const last=await getTwo(result);
const val=await getThree(last);
}catch(err){ console.log(err)}
}
如果2个操作不是继发关系,我们可以这么写,这样他们可以同时发生
async function foo(){
let [foo,bar]=await Promise.all([getFoo()],[getBar()]);
}
了解更多 ->>>>>>> http://es6.ruanyifeng.com/#docs/async