-1

I have this code in './utils/url.js'. it basically makes the application/x-www-form-urlencoded content form:

const ContentForm = ()=>{
    let params = new URLSearchParams()
    const randomString = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    params.append('email', `${randomString}@gmail.com`)
    return params;
}
module.exports = ContentForm;

The email parameter is a random string.

and index.js:

const axios = require('axios').default;
const fs = require('fs');
const params = require('./utils/url')

for (let i = 0; i < 1000; i++) {
const config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
// sending post with data of web/application the url http://somewhere.com/my-account/
axios.post('http://somewhere.com/my-account/',params(),config, {
})
    .then(function (response) {
         console.log("request successfully made")
    })  
    .catch(function (error) {
        // seeing the error response code
        console.log(error.response.status);
    })
    .finally(function () {
        // always executed
        fs.writeFileSync('./r.txt',String(i));
    })

}

So I want that the 'i' variable be written in the ./r.txt. It actually means that which request we are sending write now. but the problem is that it is really strange in it: look the video of r.txt changes here

JustAG33K
  • 1,403
  • 3
  • 13
  • 28
Mehan Alavi
  • 278
  • 3
  • 17
  • It's not clear what the problem is. Please [edit] your question to explain in plain words what you expect to happen and what actually happens. – Phil Aug 18 '22 at 07:30
  • 1
    _"look the video of r.txt changes here"_ -> [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"DO NOT post images [videos] of code, data, error messages, etc. - copy or type the text into the question. Please reserve the use of images for diagrams or demonstrating rendering bugs, things that are impossible to describe accurately via text."_ – Andreas Aug 18 '22 at 07:31
  • 1
    A (not perfect) duplicate of: [JavaScript ES6 promise for loop](https://stackoverflow.com/questions/40328932/javascript-es6-promise-for-loop) – Andreas Aug 18 '22 at 07:35
  • @Andreas - I found the video very useful and descriptive. – jfriend00 Aug 18 '22 at 07:36
  • 1
    @jfriend00 It's still an off-site resource with relevant information. And a _"the order of the `i` values in the file doesn't match the loop"_ would have the same value of information without any fancy images/videos/animations... - at least that's what I think the video shows because I'm not able to see it and that's what the code will produce – Andreas Aug 18 '22 at 07:37
  • 1
    FYI you can omit the `content-type` header customisation. Axios will use `application/x-www-form-urlencoded` by default – Phil Aug 18 '22 at 07:41

2 Answers2

1

You are running 1000 asynchronous operations in a loop. You start them sequentially, but they all run in parallel. Then as each one finishes each one calls fs.writeFileSync() and it's a race to see which one calls it when. It will be random in what order each one finishes, which is what I think your video shows.

You can sequence them to be in order using await like this:

const axios = require("axios").default;
const fs = require("fs");
const params = require("./utils/url");

async function run() {

    for (let i = 0; i < 1000; i++) {
        const config = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
        };
        // sending post with data of web/appliaction the url http://somewhere.com/my-account/
        await axios
            .post("http://somewhere.com/my-account/", params(), config, {})
            .then(function(response) {
                console.log("request succesfully made");
            })
            .catch(function(error) {
                // seeing the error response code
                console.log(error.response.status);
            })
            .finally(function() {
                // always executed
                fs.writeFileSync("./r.txt", String(i));
            });
    }
}

run().then(() => {
    console.log("done");
}).catch(err => {
    console.log(err);
});

Or, reorganized a bit to not mix await and .then() in the same function like this:

const axios = require("axios").default;
const fs = require("fs");
const params = require("./utils/url");

async function run() {
    for (let i = 0; i < 1000; i++) {
        const config = {
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
        };
        // sending post with data of web/appliaction the url http://somewhere.com/my-account/
        try {
            let response = await axios.post("http://somewhere.com/my-account/", params(), config, {});
            console.log("request succesfully made");
        } catch(error) {
            console.log(error.response.status, error);
        } finally {
            fs.writeFileSync("./r.txt", String(i));
        }
    }
}

run().then(() => {
    console.log("done");
}).catch(err => {
    console.log(err);
});
Sadeed_pv
  • 513
  • 1
  • 9
  • 22
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0
async function writeToFile(){
    for (let i = 0; i < 1000; i++) {
      const config = {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
      };
      // sending post with data of web/appliaction the url http://somewhere.com/my-account/
     await axios
        .post("http://somewhere.com/my-account/", params(), config, {})
        .then(function (response) {
          console.log("request succesfully made");
        })
        .catch(function (error) {
          // seeing the error response code
          console.log(error.response.status);
        })
        .finally(function () {
          // always executed
          fs.writeFileSync("./r.txt", String(i));
        });
    }
}