看一道面试题
题目三:
async function async1 () {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2 () {
console.log('async2');
}
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0)
async1()
new Promise (function (resolve) {
console.log('promise1')
resolve()
}).then(function () {
console.log('promise2')
})
console.log('script end')
并且 Promise.resolve('阿萨大大')!==new Promise(res=>{
res('asdddsad')
})
我也看到过有很多 await 1,其实 不管是await后面跟的是什么都会形成后面的堵塞,返回值也在微任务执行到它的时候才会返回
执行结果:
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
只要函数 前面添加 async 返回的都是 promise 三种状态 ,等待中,成功时,失败时,
async function fun(){
let data= await 1 // Promise.resolve(1).then((data)=>{})
前面 let data则就是 后面.then中的data
await 2 Promise.resolve(1).then(()=>{})
return '阿萨大大' // return Promise.resolve(阿萨大大)
}
async function async1(){
console.log('async1 start')
let add= await async3()
console.log(add)
await async2()
console.log('async1 end')
}
function async3(){
console.log('async3')
return 'async3 end'
}
async function async2(){
console.log('async start')
return new Promise(res=>{
res('4454545')
console.log('async2 promise')
})
}
console.log('script start')
setTimeout(()=>{
console.log('setTimeout')
},0)
async1()
new Promise(res=>{
console.log('promise1')
res()
}).then(()=>{
console.log('promise2')
}).then(()=>{
console.log('promise3')
})
console.log('script end')
/*答案如下
script start--->async1 start--->async3---> promise1--->script end--->async3 end--->async start--->async2 promise-->promise2--->promise3--->async1 end--->setTimeout
*/
//对于这道题的解释,因为 代码会从上往下执行,但是遇见await就会跳出async1这个函数,继续执行同步代码,然后就走到new promise执行promise1把同步代码全部执行完毕,接下来会把返回的这promise放入promise队列,又回到async1这个函数,因为
// async3函数返回的并不是promise,所以执行add=async3 end,依次执行,先进先出