我有一个中间件。作为第一步,它从 Promise.all 中的 3 个不同端点获取数据报告。
const keys = ['a', 'b', 'c'];
const getDataFromEndpoint = async (key) => {
return await ... ;
};
const [result1, result2, result3] = await Promise.all(keys.map(key => getDataFromEndpoint(key)));
这里没有问题,按预期使用 Promise.all。
然后,在步骤 2 中,它从另一个端点获取另一个报告。它还必须从第一步开始将数据合并在一起,这是一个有点繁重的同步操作。
编辑:切换顺序,以便首先调用异步函数
const mergeResults = (arrayOfResults) => {
return arrayOfResults.reduce( ... );
};
const anotherKey = 'd';
const [result4, mergedResults] = Promise.all([
getDataFromEndpoint(anotherKey),
mergeResults([result1, result2, result3]),
]);
这是否可以在异步调用等待响应的“同时”有效地运行同步代码?如果是这样,这是否比在 Promise.all 中不包含同步代码更高效?
我已经使用带有同步和异步功能的 Promise.all 实现了它,我只是不知道它是否有区别。
这是否可以在异步调用等待响应的“同时”有效地运行同步代码?
有点。
getDataFromEndpoint(anotherKey)
将开始工作并在主线程中执行,直到第一个异步操作。然后控制流将传递到下一个主线程操作mergeResults([result1, result2, result3])
。
您传递给
Promise.all()
的数组只有在后者完成后才会被实现。
这比不在 Promise.all 中包含同步代码的性能更高吗?
性能差异可能可以忽略不计,但您所拥有的是一些令人困惑的代码和
Promise.all()
的误用。
您不妨使用功能相同的这个
const results = await Promise.all(keys.map(getDataFromEndpoint));
// Start the other endpoint request
const p4 = getDataFromEndpoint('d'); // note: no `await`
const mergedResults = mergeResults(results);
const result4 = await p4; // now await the result