Promise的同步与异步

1.Promise的executor是同步的,但是then和catch方法是异步的
`const p = new Promise(resolve=>{
console.log(“1”)

setTimeout(() => {
    resolve(2)
    console.log('2')
}, 100);
console.log('3')

})
p.then(res=>{
console.log(‘4’)
})
console.log(‘5’)
// 输出:1 3 5 2 4 `
|–|--|
| | |
2.await让代码同步执行,阻塞代码
await 1;
console.log(“2”)
相当于
Promise.resolve(“1”).then(res=>{
console.log(“2”)
})

所以await会阻塞所在函数后面的代码块,但是如果await后面是异步操作,就会跳出本次函数
async function fn1(){
console.log(“1”)
await fn5();
await fn6();
}
function fn2(){
console.log(“2”)
return Promise.resolve(2.1);
}
async function fn3(){
setTimeout(() => {
console.log(“3”)
}, 3000);
}
function fn4(){
console.log(“4”)
}
function fn5(){
setTimeout(() => {
console.log(“5”)
}, 100);
}
function fn6(){
console.log(“6”)
}

fn1();
fn2();
fn3();
fn4();
// 1 2 4 6 5 3

你可能感兴趣的:(js,javascript)