相关文章推荐

详解js的宏任务与微任务(event loop)

jakearchibald.com/2015/tasks-…

怎么解决 setTimeout 和 Promise().then() 顺序先后问题

如果像这种 setTimeout 与 Promise().then() 混用的话,得使用下面这种回调,

downloadPdf() {
      // this.$refs['schedulePrint'].fixed()
    this.loading = true
    this.$nextTick(() => {
        this.$_downloadSchedulePrint('.schedulePrint', '行程文档', function() {
            this.loading = false

Promise.then() 之前先于 setTimeout()

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

2. Promise

Promise本身是同步的立即执行函数(如果一个任务已经完成,再添加回调函数,该回调函数会立即执行), 当在promise中执行resolve或者reject的时候, 此时是异步操作, 会先执行then/catch等,当主栈完成后,才会去调用resolve/reject中存放的方法执行,打印p的时候,是打印的返回结果,一个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

3. then方法

const promise = new Promise((resolve, reject) => {
    console.log(1)
    resolve()
    console.log(2)
promise.then(() => {
    console.log(3)
console.log(4)
// 输出顺序: 1 -> 2 -> 4 -> 3

promise构造函数是同步执行的,then方法是异步执行的

Promise new的时候会立即执行里面的代码 then是微任务 会在本次任务执行完的时候执行 setTimeout是宏任务 会在下次任务执行的时候执行

4. 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对象来实现同步的效果。

分类:
前端
标签:
 
推荐文章