0

I wrote following code to do that job...but it is calling only once. But i wanted to call multiple times for all object in that list. Is it possible to call any code synchronously in 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);
      })
  • 1
    *But i wanted to call multiple times for all object in that list. Is it possible to call any code synchronously in nodejs.* - what's the connection? No, you can't and you shouldn't. This is what async/await is for. What's the problem with it? – Estus Flask Mar 07 '19 at 12:38
  • Possible duplicate of [How can I make this call to request in nodejs synchronous?](https://stackoverflow.com/questions/9884418/how-can-i-make-this-call-to-request-in-nodejs-synchronous) – A Jar of Clay Mar 07 '19 at 13:50

2 Answers2

0

You can run some code in Node.js synchronously, for example you can read a file synchronously using fs.readFileSync. But you shouldn't in most cases, remember there is a reason most Node.js I/O is asynchronous.

Most APIs use this asynchronous pattern, ensuring that function calls do not block. With these function calls, such as your example above, you cannot run them synchronously, however you can use the asynch / await pattern to give you the same syntax a synchronous function would give you.

// 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();
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

You can get the result by sync way using async and 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)
})();
narayansharma91
  • 2,273
  • 1
  • 12
  • 20
  • I am calling same API multiple times with for loop for different types 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; } but it is calling only once...not sure why only once it is calling...it should call three times synchronously.. – ravindra devagiri Mar 07 '19 at 13:33