问题
我有3个函数彼此依赖,因此我希望它们按顺序运行。这些函数是异步的,返回promise并需要一定时间才能运行。
我的代码 - Index.js
#Function One
scrapA.scrap().then(data => {
readWriteToFile.writeToFile(data, 'scrapA-data-'+timestamp, 'json');
});
#Function Two
compare.compareData('./output/json/data.json', './output/json/scraped-data-'+timestamp+'.json').then(data => {
let dataWithStockData = data;
let mapDatas = dataWithStockData.map( obj => {
let finalObj = {
manufacturer: obj.manufacturer,
grade: obj.condition,
carrier: obj.carrier,
stock: obj.stock,
}
return finalObj;
});
#Function Three
readWriteToFile.writeToFile(data, 'data-with-stock-'+timestamp, 'csv'); });
我的代码 - compare.js
async function compareData(models, competitorsData) {
try {
const modelsArr = JSON.parse(fs.readFileSync(models, { encoding: 'utf8', flag: 'r' }));
const competitorsDataArr = JSON.parse(fs.readFileSync(competitorsData, { encoding: 'utf8', flag: 'r' }));
//Loop through both array of json data
modelsArr.forEach((device, deviceKey) => {
competitorsDataArr.forEach((scrapedData, scrapedDataKey) => {
if (
scrapedData.manufacturer.toLowerCase() === data.manufacturer.toLowerCase()
) {
modelsArr[dataKey]['stk'] = scrapedData.stk;
}
})
});
return modelsArr;
} catch (error) {
console.log("Error", error);
throw error;
}
}
My Code - readWriteToFile.js
async function writeToFile(data, filename, type) {
let finalData = '';
if (type == "json") {
finalData = JSON.stringify(data);
} else if (type == "csv") {
finalData = arrayToCSV(data);
} else {
console.log("File type not supported");
process.exit(1);
}
fs.writeFile("./output/" + type + '/' + filename + '.' + type, finalData, (err) => {
if (err) {
console.log(err);
} else {
console.log("File written successfully\n");
}
});
我的解决方案
我的解决方案
我只是简单地在所有的函数调用中添加了async并在前面加上了await。它没有起作用,也没有抛出任何错误。
(async () => {
await scraperA.scrap().then(data => {
console.log("DATA", data);
readWriteToFile.writeToFile(data, 'scraped-data-'+timestamp, 'json');
});
await compare.compareData('./output/json/data.json', './output/json/scraped-data-'+timestamp+'.json').then(data => {
let dataWithStockData = data;
mapData = dataWithStock.map( obj => {
let finalObj = {
manufacturer: obj.manufacturer,
grade: obj.condition,
stock: obj.stock,
}
return finalObj;
});
});
await readWriteToFile.writeToFile(mapData, 'data-with-stock-'+timestamp, 'csv');
});