Home > Software design >  how to save the result of a loop in JSON?
how to save the result of a loop in JSON?

Time:03-07

I have created a loop in an asynchronous function that gets data from an external page. I would like the result to be saved in JSON. However, my script doesn't work as expected.

for (let tokenId = 0; tokenId < 5; tokenId  ) {
    try{
        let result = await Gateway.tokenURI(tokenId);
        console.log(result);
        fs.writeFileSync("ogUris.json", result)
    }catch(e){
      console.log(e)
    }
  
  }

CodePudding user response:

You are calling fs.writeFileSync() inside your loop where each call to that function will replace/overwrite the previous results.

If you want to save an array of results in your JSON, then you can accumulate the results into an array and then write the array at the end.

const results = [];
for (let tokenId = 0; tokenId < 5; tokenId  ) {
    try {
        let result = await Gateway.tokenURI(tokenId);
        results.push(result);
    } catch(e) {
        console.log(e);
    }
 }
 fs.writeFileSync("ogUris.json", JSON.stringify(results));

This will leave you with an array of tokenURIs in JSON format in the file.

CodePudding user response:

This is not working because for loop doesn't wait for await Gateway.tokenURI(tokenId) to provide you any response.You can try using promise.all

  • Related