0

I am working on a python project and need to get some data from a Node.js API, so I try to code some node.js which I just have little knowledge about it.

My code is like:

const SneaksAPI = require('sneaks-api');
const sneaks = new SneaksAPI();
const fs = require('fs');

let idList = ["FY2903", "FZ5246", "FZ5421"];

for (var shoeID of idList){
    sneaks.getProductPrices(shoeID, function(err, product){
        var data = JSON.stringify(product, null, 2);
        fs.writeFile(`/Users/sam/Downloads/${shoeID}.json`, data, (err) => {
            if (err) throw err;
            console.log(`The file ${shoeID}.json has been saved!`);
        });
    });
} 

It seems that something goes wrong in the loop... the output is like:

The file FZ5421.json has been saved!
The file FZ5421.json has been saved!
The file FZ5421.json has been saved!

Only the last element in the idList is assigned and when I open the json file I find that the content actually belongs to the second element "FZ5246"...

I am sure there's something wrong with the code...Any one can help me to figure this out?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
kroos
  • 37
  • 6

1 Answers1

0

Your loop was a bit funny. I haven't seen that syntax in Node.js before. Although it seemed to kind of work ok on a basic loop, your issue was resolvable by using forEach() instead. I also added a rethrow in the upper callback if it's needed (you were only rethrowing the most nested error)

const SneaksAPI = require("sneaks-api");
const sneaks = new SneaksAPI();
const fs = require("fs");

let idList = ["FY2903", "FZ5246", "FZ5421"];

idList.forEach((shoeID) => {
    sneaks.getProductPrices(shoeID, function (error, product) {
        if (error) throw error;
        var data = JSON.stringify(product);
        fs.writeFile(`/Users/sam/Downloads/${shoeID}.json`, data, (err) => {
            if (err) throw err;
            console.log(`The file ${shoeID}.json has been saved!`);
        });
    });
});
defraggled
  • 1,014
  • 11
  • 13