You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
alanwhy, Anaxagoras648, Paladin-YGF, jcyicai, houshaoxuan and 20 more1783883121, goodboyfrank, MargaretMao and jobsofferingszhangshishui, wfc2969180378, LuoRiWuSheng and bettersongcaojikeai and herikyXuanZhenJun, solaliuqi, tinytot1, liujiahuilala, hhqaq and 4 more
rujinshi, KaiOrange, kuanke, chen86860, wsfy15 and 177 moreddzyvijav, JackZs and wepn13232rujinshi, JerryYanzhiwei, zhongxia245, hookbin, banxia12581 and 8 moreJackZsguanrunkai and sheng-sndJackZs and Srawzlaclys, ChaseUp, banxia12581, JackyLeeCS, xuetupeng and 8 more
Activity
JJL-SH commentedon Mar 11, 2019
宏观任务队列
微观任务队列
的区别
sisterAn commentedon Mar 11, 2019
1. setTimeout
2. Promise
Promise本身是同步的立即执行函数, 当在executor中执行resolve或者reject的时候, 此时是异步操作, 会先执行then/catch等,当主栈完成后,才会去调用resolve/reject中存放的方法执行,打印p的时候,是打印的返回结果,一个Promise实例。
当JS主线程执行到Promise对象时,
promise1.then() 的回调就是一个 task
promise1 是 resolved或rejected: 那这个 task 就会放入当前事件循环回合的 microtask queue
promise1 是 pending: 这个 task 就会放入 事件循环的未来的某个(可能下一个)回合的 microtask queue 中
setTimeout 的回调也是个 task ,它会被放入 macrotask queue 即使是 0ms 的情况
3. async/await
async 函数返回一个 Promise 对象,当函数执行的时候,一旦遇到 await 就会先返回,等到触发的异步操作完成,再执行函数体内后面的语句。可以理解为,是让出了线程,跳出了 async 函数体。
举个例子:
很显然,func1的运行结果其实就是一个Promise对象。因此我们也可以使用then来处理后续逻辑。
await的含义为等待,也就是 async 函数需要等待await后的函数执行完成并且有了返回结果(Promise对象)之后,才能继续执行下面的代码。await通过返回一个Promise对象来实现同步的效果。
更多可见setTimeout、Promise、Async/Await
Fengziyin1234 commentedon Mar 29, 2019
上面的解释都很详细了。
我拿 babel es8 编译了下 async/await 结果是这样的
--->
await/async 是通过 Generator/function* 来实现的。 所以 async/await 的相关优势也来自于generator。 Generator 是一个可以暂停 function ,感觉推出 generator 的目的包括不仅限于 Callback Hell 和 Inversion of Control。 感觉整个 community 有在往那个方向走。
结果如下
MrRENGE commentedon Apr 6, 2019
[-]第八题:setTimeout、Promise、Async/Await 的区别[/-][+]第8题:setTimeout、Promise、Async/Await 的区别[/+][-]第8题:setTimeout、Promise、Async/Await 的区别[/-][+]第 8 题:setTimeout、Promise、Async/Await 的区别[/+]song-le-yi commentedon Jul 16, 2019
有个问题,如果promise的finally方法里面出错了怎么办呀,怎么捕获呀?
MrRENGE commentedon Jul 16, 2019
会返回一个 被reject 的promise对象。继续绑定catch函数可以捕获到
xuetupeng commentedon Jul 20, 2019
写的很好,感谢大大的分享,我还有一个疑惑上面提到的Async/Await await执行的代码 ,会跳出线程,但是await上面的打印会出现在await执行打印的前面,意思是await前面的代码都会跳出线程(异步执行),只有await后面的代码才是同步执行这个意思吗?
rzh11111111 commentedon Jul 30, 2019
宏观微观?我记得promise的执行是在setimeout之前(好像),async/await是基于promise的
xuetupeng commentedon Jul 30, 2019
宏观吧,我其实就是比较奇怪,await前面的代码都跳出了线程吗,还是单纯就await 后面的执行跳出了线程, 也可能是我表达有问题, 为啥await以及前面代码的都会先打印 然后才是跳出线程执行外面的,最后才执行await下面的代码。
rzh11111111 commentedon Jul 30, 2019
就像setimeout是1,2,3这样的顺序来的,但是promise是1.1,1.2,promise是微观的,async,await基于promise也大概和promise一样
xuetupeng commentedon Jul 30, 2019
27 remaining items