async 函数

同步
console.log(1);
console.log(2);
console.log(3);
console.log(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和结束;

posted @ 2017-07-19 21:07  前端兵哥哥  阅读(1582)  评论(0)    收藏  举报