async函数(asynchronous 异步的)
同步:
console.log(1);
console.log(2);
console.log(3);
console.log(4);
//依次打印1 2 3 4;
异步 ajax 文件读取io操作:
console.log(1);
console.log(2);
setTimeout(function(){
console.log(3000);
},3000);
console.log(3);
console.log(4);
//先打印1 2 3 4,隔三秒后打印3000;
async函数返回的是resolve状态的Promise对象:
async function fn(){
return "abc";
}
let result=fn();
console.log(result);//打印:Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "abc"}。
Promise 对象:
let p = new Promise(function(resolve,reject){
resolve("abc");
});
p.then(function(data){
console.log(data);//打印abc。
});
async函数里面的返回值传递给then方法:
async function fn(){
return "123";
}
let p1 = fn();
p1.then(function(data){
console.log(data);//打印123.
});
async函数用来处理异步:
function one(){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log("one_3000");
resolve("one_3000");
},3000);
})
}
function two(){
return new Promise(function(resolve,reject){
setTimeout(function(){
console.log("two_2000");
resolve("two_2000");
},2000);
})
}
//await只能出现在异步函数里面,
async function shunxu(){
console.log("start");
let r1 = await one();
console.log(r1);
let r2 = await two();
console.log(r2);
return "end";
}
let p3 = shunxu();
p3.then(r=>{
console.log("结束");
});
//先打印start,三秒后打印两次one_3000,打印完one_3000然后隔两秒打印两次two_2000和结束;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。