Node.js 如何确保在函数返回之前执行所有行
从index.js调用readCSVNode.js 如何确保在函数返回之前执行所有行,node.js,asynchronous,async-await,Node.js,Asynchronous,Async Await,从index.js调用readCSV const productIds = await readCSV(); 在另一个文件中: async function readCSV() { const filepath = path.resolve('src/input_csv.csv'); const readstream = await fs.createReadStream(filepath); const stream = await reads
const productIds = await readCSV();
在另一个文件中:
async function readCSV() {
const filepath = path.resolve('src/input_csv.csv');
const readstream = await fs.createReadStream(filepath);
const stream = await readstream.pipe(parser());
let productIds = [];
await stream.on('data', data => {
productIds.push(data.SourceProductId);
console.log('SourceProductId', data.SourceProductId);
});
await stream.on('end', () => {
console.log(productIds);
});
if (productIds.length > 0) return productIds;
else return 'no products found';
});
}
它给出了输出:
in main: []
SourceProductId 1000050429
SourceProductId 1132353
SourceProductId 999915195
SourceProductId 50162873
SourceProductId 1000661087
[ '1000050429', '1132353', '999915195', '50162873', '1000661087' ]
我希望函数返回从CSV读取的所有值的数组。但是,在执行stream.on语句之前,它似乎正在返回。如何确保在返回之前执行所有行。我把等待放在每一句话之前,但是没有运气。stream.on不会返回承诺,所以你不能等待它
您可以通过从readCSV函数返回承诺来解决此问题:
function readCSV() {
return new Promise(resolve => {
const filepath = path.resolve('src/input_csv.csv');
const readstream = fs.createReadStream(filepath);
const stream = readstream.pipe(parser());
let productIds = [];
stream.on('data', data => {
productIds.push(data.SourceProductId);
console.log('SourceProductId', data.SourceProductId);
});
stream.on('end', () => {
console.log(productIds);
if (productIds.length > 0) resolve(productIds);
else resolve('no products found');
});
});
}
通过将回调函数作为参数传递来创建承诺。该回调函数获取一个参数resolve,它是在异步操作完成时调用的另一个回调函数,用于传递结果
在上面的示例中,我们在文件读取流完成后使用产品ID调用此resolve回调
由于readCSV现在返回承诺,您可以像在代码示例中那样等待它:
const productIds = await readCSV();
async/await仅适用于类似Promise的对象。溪流不是那样的。在将wait关键字散布到代码中之前,您需要了解承诺。例如wait fs.createReadStreamfilepath您在这里等待什么?如何确保流在返回之前完成?我已经添加了这些内容作为调试的一部分,现在我已经删除了这些内容。您需要创建一个承诺,该承诺将在流结束时得到解决。我添加了一些解释,以明确发生了什么