如何在接收到响应值后通过同时执行两个异步函数来执行该函数


export default {
data: () =>({
data1: [],
data2: [],
lastData: []
}),
mounted() {
asynchronous1(val, (data)=>{
return this.data1 = data
})
asynchronous2(val, (data)=>{
return this.data2 = data
})
function lastFuction() {
this.lastData = this.data1.concat(this.data2)
}
},
}

在同时执行asynchronous1和asynchronous 2之后,我想在收到这两个响应值后执行lastFution。

假设asynchronous1和asynchronous 2不返回Promises,这很可能是因为它们采用了回调函数

你可以做这个(混乱的(

export default {
data: () =>({
data1: [],
data2: [],
lastData: []
}),
mounted() {
let lastFunction = (() => {
let count = 0;
return () => {
count++;
if (count === 2) {
this.lastData = this.data1.concat(this.data2);
}
};
})();
asynchronous1(val, (data) => {
this.data1 = data;
lastFunction();
})
asynchronous2(val, (data) => {
this.data2 = data;
lastFunction();
})
},
}

但它会工作

更好的解决方案是使用async/await和Promises

export default {
data: () =>({
data1: [],
data2: [],
lastData: []
}),
async mounted() {
const p1 = new Promise(resolve => {
asynchronous1(val, (data) => {
this.data1 = data;
resolve();
})
});
const p2 = new Promise(resolve => {
asynchronous2(val, (data) => {
this.data2 = data;
resolve();
})
});
await Promise.all([p1, p2]);
this.lastData = this.data1.concat(this.data2);
},
}

不过,我可能会走得更远:

export default {
data: () =>({
data1: [],
data2: [],
lastData: []
}),
async mounted() {
const promisify = fn => (...args) => new Promise(resolve => fn(...args, resolve));

const p1 = promisify(asynchronous1);
const p2 = promisify(asynchronous2);
const [r1, r2] = await Promise.all([p1(val), p2(val)]);
this.data1 = r1;
this.data2 = r2;
this.lastData = [...r1, ...r2];
},
}

这里的区别在于,this.data1/this.data2在两个异步函数完成之前不会被填充——这可能不符合的喜好

你可以做

const [r1, r2] = await Promise.all([
p1(val).then(r => this.data1 = r), 
p2(val).then(r => this.data2 = r)
]);

而不是

const [r1, r2] = await Promise.all([p1(val), p2(val)]);
this.data1 = r1;
this.data2 = r2;

这将使它以与原始代码相同的方式填充-我只是讨厌使用async/await AND。然后……但在某些边缘情况下,它比纯async/await更好-在我看来

当然,如果asynchronous1/2可以返回一个promise,如果你不指定回调函数(现在越来越常见(,那么代码可能会更简单

const [r1, r2] = await Promise.all([asynchronous1(val), asynchronous2(val)]);

而不是

const p1 = promisify(asynchronous1);
const p2 = promisify(asynchronous2);
const [r1, r2] = await Promise.all([p1(val), p2(val)]);

你可以有这样的东西:

async function func1() { ... }
async function func2() { ... }
async function func3() { ... }
async function main() {
await Promise.all([func1, func2]);
await func3();
}

最新更新