了解这种情况会如何产生错误,印刷。 该方法末的标识。
2. 一般性问题:
- Arbitrary order.
- printFiles can finish running before printing files.
- Poor performance.
这些情况并不总是错的,但经常出现在标准使用案件中。
一般说来,除最后一点外,使用每个目标都将产生结果。 它把每个职能称为每个职能,而不必等待其职能的含义,即它把所有职能开始,而不必等待完成。
import fs from fs-promise
async function printFiles () {
const files = (await getFilePaths()).map(file => fs.readFile(file, utf8 ))
for(const file of files)
console.log(await file)
}
printFiles()
这是土著共同提交文件的一个实例,它将维护秩序,防止职能提前恢复,理论上保持最佳业绩。
这将:
- Initiate all of the file reads to happen in parallel.
- Preserve the order via the use of map to map file names to promises to wait for.
- Wait for each promise in the order defined by the array.
有了这一解决办法,第1个档案一经提供就将立即显示,而不必等到其他文件才能提供。
它还将同时装上所有档案,而不是等到第一件档案开始之前完成。
这和最初版本的唯一回馈是,如果一开始多读,则由于当时可能会发生更多的错误,更难以处理错误。
文本在当时读到档案后,将停止失败,而没有浪费时间试图阅读更多的档案。 即便有一套详细的注销制度,也很难避免在第一份档案中出现故障,但已经阅读了大多数其他档案。
Performance is not always predictable. While many systems will be faster with parallel file reads some will prefer sequential. Some are dynamic and may shift under load, optimisations that offer latency do not always yield good throughput under heavy contention.
这方面也没有错误处理。 如果有些事情要求他们要么成功展示,要么根本不成功,那就失败了。
建议对青.进行深度试验。 每一阶段的标识和假文件为解决办法(总是拖延)。 虽然在简单情况下,许多解决办法似乎都是一样的,但都存在微妙的差别,需要一些额外的审查才能消除。
Use this mock to help tell the difference between solutions:
(async () => {
const start = +new Date();
const mock = () => {
return {
fs: {readFile: file => new Promise((resolve, reject) => {
// Instead of this just make three files and try each timing arrangement.
// IE, all same, [100, 200, 300], [300, 200, 100], [100, 300, 200], etc.
const time = Math.round(100 + Math.random() * 4900);
console.log(`Read of ${file} started at ${new Date() - start} and will take ${time}ms.`)
setTimeout(() => {
// Bonus material here if random reject instead.
console.log(`Read of ${file} finished, resolving promise at ${new Date() - start}.`);
resolve(file);
}, time);
})},
console: {log: file => console.log(`Console Log of ${file} finished at ${new Date() - start}.`)},
getFilePaths: () => [ A , B , C , D , E ]
};
};
const printFiles = (({fs, console, getFilePaths}) => {
return async function() {
const files = (await getFilePaths()).map(file => fs.readFile(file, utf8 ));
for(const file of files)
console.log(await file);
};
})(mock());
console.log(`Running at ${new Date() - start}`);
await printFiles();
console.log(`Finished running at ${new Date() - start}`);
})();