先久闻async、await,今日终于天时、地利、人和来一睹芳容。
先来看一列
代码片段:
async function test() {
const response = await new Promise(resolve => {
setTimeout(() => {
resolve("test");
}, 1000);
});
console.log(response);
}
test();
输出结果:
test
疑问:response居然拿到了promise的resolve返回值"test"?
对比例子一:
代码片段:
function test() {
const response = new Promise(resolve => {
setTimeout(() => {
resolve("test");
}, 1000);
});
console.log(response);
}
test();
输出结果:
Promise {<pending>}
结果分析:new Promise返回Promise对象赋值于response,既然如此为何文章开始列子使用async、await便可拿到promise对象的resolve返回值?那当然是因为…我也不知道,以后知道了再补充。
对比例子二:
代码片段:
async function test() {
console.time('asyncStart')
const response = await new Promise(resolve => {
setTimeout(() => {
resolve("test");
}, 1000);
});
console.timeEnd('asyncStart')
console.log(response);
}
test();
输出结果:
asyncStart: 1000.716064453125ms
test
结果分析:await new Promise…代码片段执行时长将近一秒,极像const response = “test”。亦由此可知async、await为何像同步写法。
传闻koa使用async、await解决了express回调地狱,既然如此咱们便比较比较。
代码片段:
//回调
function start(a,cb){
new Promise(resolve=>{
setTimeout(()=>{
resolve(a)
},1000)
})
.then((result)=>{
new Promise(resolve=>{
setTimeout(()=>{
resolve(result)
},1000)
})
.then((res)=>{
cb(res);
})
})
}
start(1,function(res){console.log(res)})
// async、await
async function test(b,cb){
var result = await new Promise(resolve=>{
setTimeout(()=>{
resolve(b)
},1000)
})
var res = await new Promise(resolve=>{
setTimeout(()=>{
resolve(result)
},1000)
})
cb(res)
}
test(2,function(res){console.log(res)})
输出结果:
1
2
结果分析:不用多说,自己感受,这仅仅是两层而已。
再来感受一段有意思的
代码片段:
async function test(str) {
return await new Promise(resolve => {
setTimeout(() => {
resolve(str)
}, 1000);
})
}
async function a(){
console.time('a')
console.log(await test('a--str1'));
console.log(await test('a--str2'));
console.timeEnd('a')
}
a();
async function b(){
console.time('b')
var b1 = test('b--str1');
var b2 = test('b--str2')
console.log(await b1);
console.log(await b2);
console.timeEnd('b')
}
b();
输出结果:
a--str1
b--str1
b--str2
b: 1004.19384765625ms
a--str2
a: 2004.85498046875ms