async/await实现异步
await表示等一下,即暂停不再向下执行,等到promise对象执行完毕, 拿到promise resolve的值并进行返回,拿到返回值后再继续向下执行
下面来看几个例子
async function async_test() {
return 'hello world'
}
async_test();
// console.log(async_test()) // Promise {<fulfilled>: "hello world"}
async_test().then(result => {
console.log(result); // 这样就可以得到async_test的值了,即hello world
})
console.log('虽然在后面,但是我先执行');
3s后得到result的值,即60
function async_test(num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2 * num)
}, 3000);
})
}
async function testResult() {
let result = await async_test(30);
console.log(result); // 60
console.log(222)
}
testResult();
3s后会先糖出alert,在这之前并没有打印出2222,等alert执行完后,才会看到打印出了2222
function await_push() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(
sessionStorage.setItem('async_await','testdata'),
alert(111111111)
)
}, 3000);
})
};
async function async_push() {
await this.await_push()
console.log(22222)
};
async_push()