gpt4 book ai didi

javascript - 如何在继续之前等待所有文件被读取并执行所有回调

转载 作者:行者123 更新时间:2023-12-02 23:18:23 24 4
gpt4 key购买 nike

我正在使用 node.js 并尝试同时读取 3 个 xlsx 文件,并且仅当所有 3 个文件均已读取并执行回调时,才以数组形式返回所有文件。

我尝试使用 Promise.all 但我在回调完成之前获取了数组。

这是代码

const path = require('path');
const extractor = require("xlsx-to-json");

(async () =>{
let x = [];

const dir = 'my/path';

const files = [
{ name:'File1.xlsx'},
{ name:'File2.xlsx' },
{ name:'File3.xlsx'}
];

await Promise.all(
files.map(async (file)=>{
console.log('init: %s',file.name);
let start = new Date();

let filePath = path.resolve(dir,file.name);

extractor({
input: filePath,
output: null
}, function(err, result) {
if(err) {
console.error(err);
} else {
x.push(result);
let end = new Date() - start;
console.info('Extraction time of [%s]: %dms', file.name, end);
}
});
})
);
console.log(x);
})();

我需要的输出是:

init: File1.xlsx
init: File2.xlsx
init: File3.xlsx
Extraction time of [File1.xlsx]: 17233ms
Extraction time of [File2.xlsx]: 16615ms
Extraction time of [File3.xlsx]: 15266ms
[ some json objects ]

但我得到以下信息:

init: File1.xlsx
init: File2.xlsx
init: File3.xlsx
[] //empty array
Extraction time of [File1.xlsx]: 17233ms
Extraction time of [File2.xlsx]: 16615ms
Extraction time of [File3.xlsx]: 15266ms

最佳答案

使用Promise.all是正确的,但你没有正确使用它。

请参阅下面的内嵌评论

const path = require('path');
const extractor = require("xlsx-to-json");

(async () => {
//let x = [];

const dir = 'my/path';

const files = [
{ name: 'File1.xlsx' },
{ name: 'File2.xlsx' },
{ name: 'File3.xlsx' }
];

// all 3 extracted results will be returned from `await Promise.all()`
let x = await Promise.all(

// `async` not needed here
files.map(/*async*/ (file) => {
console.log('init: %s', file.name);
let start = new Date();

let filePath = path.resolve(dir, file.name);

// Promise wrapper
return new Promise((resolve, reject) => {
extractor({
input: filePath,
output: null
}, function (err, result) {
if (err) {
console.error(err);

// return error by rejecting the Promise
reject(err);

} else {
// x.push(result);

// return result by resolving the Promise
resolve(result);

let end = new Date() - start;
console.info('Extraction time of [%s]: %dms', file.name, end);
}
});
});
})
);

console.log(x);
})();

关于javascript - 如何在继续之前等待所有文件被读取并执行所有回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57059507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com