Await和Async其实就是promise的封装,使用编译技术自动将Await/Async转化为promise,为了更好的理解Await,Async是什么?我们使用转换工具来分析
async/await转换工具安装
$ sudo npm install babel-plugin-async-to-promises -g
$ babel --plugins async-to-promises async_test.js
function getConstant() {
return 1
}
async function getAsyncConstant() {
return 1
}
async function getPromise() {
return new Promise((resolved, rejected)=> {
resolved(1)
});
}
async function test() {
a = 2
c = 1
await getConstant();
d = 3
await getPromise();
d = 4
await getAsyncConstant();
return 2
}
|
function getConstant() {
return 1;
}
function getAsyncConstant() {
return Promise.resolve().then(function () {
return 1;
});
}
function getPromise() {
return Promise.resolve().then(function () {
return new Promise((resolved, rejected) => {
resolved(1);
});
});
}
function test() {
return Promise.resolve().then(function () {
a = 2;
c = 1;
return getConstant();
}).then(function () {
d = 3;
return getPromise();
}).then(function () {
d = 4;
return getAsyncConstant();
}).then(function () {
return 2;
});
}
|
从上可知, 所有带async function 的都会主动生成Promise, await会主动生成then
/********************************
* 本文来自CSDN博主"爱踢门"
******************************************/