May await an asynchronous with the expression (e.g., expression promise), may be followed by a regular expression (eg: console.log (123))
Example 1: If the immediately await a promise not resolve the object, the subsequent code will not be executed. Such as:
async function a(){
// 如果await后是promise对象
await new Promise(resolve => {
console.log(66666)
})
console.log(1)
}
a();
Promise.resolve().then(()=>{
console.log(3)
})
operation result:
运行结果:
66666
3
Here we must note, console.log (1) will not be executed, because
async function a(){
// 如果await紧跟一个普通表达式
await console.log(1);
console.log(2)
}
Equivalent to
async function a(){
new Promise(resolve => {
console.log(1)
}).then(() => {
console.log(2)
})
}
Since there is no state Promise not resolved, it will not perform subsequent .then code.
Run process diagram:
Examples 2: Promise if the object await followed an already resolved the
async function a(){
// 如果await紧跟一个已经resolved的promise对象
await new Promise(resolve => {
resolve();
console.log(66666)
})
console.log(1)
}
a();
Promise.resolve().then(()=>{
console.log(3)
})
operation result:
运行结果:
66666
1
3
Run process diagram:
Example 3: After await followed by a regular expression
async function a(){
// 如果await紧跟一个普通表达式
await console.log(1);
console.log(2)
}
a();
Promise.resolve().then(()=>{
console.log(3)
})
operation result:
运行结果:
1
2
3
Run process diagram:
Example 4: A more complex example
function c(){
return new Promise((resolve)=>{
console.log('开始了')
resolve()
}).then(()=> {
console.log('c.......');
return 65666
}).then(res => {
console.log(res);
return '返回了一个值'
})
}
async function a(){
// 如果await后的表达式是一个promise对象
await c().then((res)=>{
console.log('then....' + res)
})
console.log(1)
}
a();
console.log('同步代码')
Promise.resolve().then(()=>{
console.log(3)
})
operation result:
'开始了'
'同步代码'
'c.......'
3
65666
'then....返回了一个值'
1
Run process diagram:
Example 9: