async、await、promise用法举例
例子1:
function one() {
return 'i am one';
}
function two() {
setTimeout(() => {
return 'i am two';
}, 1000);
}
function three() {
return 'i am three';
}
function run() {
console.log(one());
console.log(two());
console.log(three());
}
run();
输出结果
i am one
undefined
i am three
缺点:对于异步操作,无法同步输出结果的缺陷
例子2:
function one() {
return 'i am one';
}
function two() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('i am two')
}, 3000)
})
}
function three() {
return 'i am three';
}
async function run() {
console.log(one());
console.log(await two());
console.log(three());
}
run();
输出结果
i am one
i am two
i am three
功能:能够实现将异步变为同步的过程