async/await implements asynchronous
Await means wait, that is, it pauses and no longer executes downwards until the promise object is executed. Get the value of promise resolve and return it. After getting the return value, continue execution.
Let’s look at some examples
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('虽然在后面,但是我先执行');
After 3s, the value of result is obtained, which is 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();
After 3 seconds, the alert will be printed first. Before that, 2222 is not printed. Only after the alert is executed, will you see 2222 printed.
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()