Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

setTimeout、Promise、Async/Await 的区别 #25

Open
madfour opened this issue Feb 25, 2021 · 1 comment
Open

setTimeout、Promise、Async/Await 的区别 #25

madfour opened this issue Feb 25, 2021 · 1 comment
Labels

Comments

@madfour
Copy link
Owner

madfour commented Feb 25, 2021

这三者主要是在事件循环中的区别,事件循环中分为宏任务和微任务队列

其中setTimeout的回调函数放到宏任务队列里,等到执行栈清空后执行;

promise.then里的函数会放到相应宏任务的微任务队列里,等宏任务里面的同步代码执行完后执行;

async函数表示函数里面可能会有异步方法,await后面跟一个表达式,async方法执行完后,遇到await会立即执行表达式,然后让表达式的代码放到微任务队列里,让出执行栈 让同步代码先执行。

代码讲解

1. setTimeout

console.log('script start')	//1. 打印 script start
setTimeout(function(){
    console.log('settimeout')	// 4. 打印 settimeout
})	// 2. 调用 setTimeout 函数,并定义其完成后执行的回调函数
console.log('script end')	//3. 打印 script start

输出顺序:script start -> script end -> settimeout
setTimeout()就是个异步任务。在所有同步任务执行完之前,任何的异步任务是不会执行的。

2. Promise

Promise本身是同步的立即执行函数

当在 宏任务 中执行 resolve 或者 reject 的时候, 此时是异步操作, 会先执行 then/catch 等,

当主栈完成后,才会去调用 resolve/reject 中存放的方法执行,打印的时候,是打印的返回结果,一个Promise实例。

console.log('script start')
let promise1 = new Promise(function (resolve) {
    console.log('promise1')
    resolve()
    console.log('promise1 end')
}).then(function () {
    console.log('promise2')
})
setTimeout(function(){
    console.log('settimeout')
})
console.log('script end')
// 输出顺序: script start -> promise1 -> promise1 end -> script end -> promise2 -> settimeout

当JS主线程执行到Promise对象时,

  • promise1.then() 的回调就是一个任务

  • promise1resolved或rejected: 那这个任务就会放入当前事件循环回合的任务队列

  • promise1pending: 这个 任务 就会放入事件循环的未来的某个(可能下一个)回合的任务队列中

  • setTimeout 的回调也是个任务 ,它会被放入任务队列即使是 0ms 的情况

3. async/await

async function async1() {
	console.log('async1-start');
	await async2();
	console.log('async1-end')
}
async function async2() {
	console.log('async2')
}

console.log('script start');
async1();
console.log('script end')

// 输出顺序
// script start
// async1-start
// async2
// script end
// async1-end

async 函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再执行函数体内后面的语句。可以理解为,是让出了线程,跳出了 async 函数体。

await 的含义为等待,也就是 async 函数需要等待 await 后的函数执行完成,并且有了返回结果(Promise对象)之后,才能继续执行下面的代码。await通过返回一个 Promise 对象来实现同步的效果。

@madfour madfour added the 异步 label Feb 25, 2021
@madfour
Copy link
Owner Author

madfour commented Feb 25, 2021

更多详解请看:setTimeout、Promise、Async/Await

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant