为什么vue2中$emit和asnyc的行为与普通函数不一样?

问题描述 投票:0回答:1

为了方便重现,我使用openpen来演示。

function foo() {
    return new Promise(resolve => {
        setTimeout(resolve, 3000);
    });
}

Vue.component('child', {
    template: '<div @click="handleClick">Click</div>',
  
    methods: {
        async handleClick() {
            console.log(1);
            const a = await this.$emit('abc');
            console.log(2);
        }
    }
});

//Root Instance
new Vue({
    el: '#app',
    template: '<child @abc="handleAbc" />',
    data: {},
    methods: {
        async handleAbc() {
            console.log(3);
            await foo();
            console.log(4);
        }
    }
})

如果我单击 div,结果是 1 3 2 4。

function foo() {
    return new Promise((resolve) => {
        setTimeout(resolve, 3000);
    });
}

async function foo1() {
    console.log(3);
    await foo();`abc`
    console.log(4);
}

async function foo2() {
    console.log(1);
    await foo1();
    console.log(2);
}
foo2();

如果我使用普通函数,结果是 1 3 4 2。

有人可以解释一下结果不一样的原因吗

vuejs2 emit
1个回答
0
投票

$emit
不返回 Promise,在其前面加上
await
表示在处理所有排队的操作后继续。

功能上,与此相同(数字按打印顺序排列):

async function action(){
  console.log(1)
  await emit() // <--- run emit and put in queue
  console.log(5)
}

function emit(){
  console.log(2)
  handler() // <--- regular function call, continues when handler() returns
  console.log(4)
}

async function handler(){
  console.log(3)
  await new Promise(setTimeout) // <--- return Promise, put in queue
  console.log(6)
}

action()

请注意,排队的项目是按顺序处理的,因此

action()
将在
handler()
之前继续。


在第二个示例中,等待的函数确实返回一个 Promise,当 Promise 解析时,执行将继续。当您将

async/await
替换为
.then()
(按打印顺序排列的数字)时,顺序就会变得明显:

function action(){
  console.log(1)
  return handler().then(() => {
    console.log(4)
  })
}

function handler(){
  console.log(2)
  return Promise.resolve().then(() => {
    console.log(3)
  })
}

action()

© www.soinside.com 2019 - 2024. All rights reserved.