我编写了以下代码来完成这项工作...但是它只调用一次。但是我想多次调用该列表中的所有对象。是否可以在nodejs中同步调用任何代码。
async function processObjs(){
var response = "done";
for(var i = 0; i < objectsToProcess.length; ++i) {
var obj = objectsToProcess[i];
await processObject(obj);
console.log("done for : " + obj);
}
return response;
}
function processObject(objectType){
var filePath = objectType+".csv";
return newPromise(objectType,filePath);
}
function newPromise(objectType,filePath){
return new Promise(function (resolve){
//following code should run synchronously
dataStore= new DataLakeStore(objectType);
let firstPage = true;
console.log("start processing for object :"+objectType);
dataStore.search(qry).forEachPage(page => {
const jsonToWrite = page.hits.map(record => {
return record._source.doc;
});
let csvData;
let flag;
if (firstPage) {
firstPage = false;
flag = "ax+";
csvData = json2csv(jsonToWrite);
}else{
flag = "a";
csvData = json2csv(jsonToWrite, { header: false }) + "\n";
}
fs.writeFileSync(filePath, csvData, { flag });
});
resolve("DONE");
});
}
processObjs().then(function (response) {
console.log("Completed FOR All " + response);
})
答案 0 :(得分:0)
您可以在Node.js中同步运行一些代码,例如,您可以使用fs.readFileSync同步读取文件。但是您在大多数情况下应该,请记住,大多数Node.js I / O都是异步的。
大多数API使用此异步模式,以确保函数调用不会阻塞。对于这些函数调用,例如上面的示例,您无法同步运行它们,但是可以使用asynch / await模式为您提供同步函数将为您提供的相同语法。
// Simulate say a DB or REST call here..
function asynchReadSomeData(callback) {
setInterval(() => {
callback("OK");
}, 2000);
}
function asynchReadSomeDataPromise() {
return new Promise((resolve) => {
asynchReadSomeData((result) => resolve(result));
});
}
async function testAwait() {
/* We can use very similar syntax to a synchonous function call here..*/
console.log("Calling asynchReadSomeDataPromise, waiting for result...");
let result = await asynchReadSomeDataPromise();
console.log("Result: ", result);
}
testAwait();
答案 1 :(得分:0)
您可以使用async和await通过同步方式获得结果。
async function processObject(objectType){
var filePath = objectType+".csv";
return await newPromise(objectType,filePath);
}
function newPromise(objectType,filePath){
return new Promise(function (resolve){
//following code should run synchronously
dataStore= new DataLakeStore(objectType);
let firstPage = true;
console.log("start processing for object :"+objectType);
dataStore.search(qry).forEachPage(page => {
const jsonToWrite = page.hits.map(record => {
return record._source.doc;
});
let csvData;
let flag;
if (firstPage) {
firstPage = false;
flag = "ax+";
csvData = json2csv(jsonToWrite);
}else{
flag = "a";
csvData = json2csv(jsonToWrite, { header: false }) + "\n";
}
fs.writeFileSync(filePath, csvData, { flag });
});
resolve("DONE");
});
}
(async () => {
const result = await processObjs();
console.log(result)
})();