beingalex
beingalex

Reputation: 2476

Javascript Promises and the map function

I am trying to loop through an array and send the value server-side. Issue is that the server side returns the same result every time.

let sms = {
    division: "",
};

Promise.all(['division_one','division_two','division_three','division_four'].map(function(division) {

    sms.division = division;

    console.log(sms);

    axios.post('http://localhost:3000/inbound', {
        sms
    })
        .then(function (response) {
            return response;
        });


})).then(function(results) {

})

Client side result:

{ division: 'division_one' }
{ division: 'division_two' }
{ division: 'division_three' }
{ division: 'division_four' }

Server side result:

{ sms: { division: '**division_four**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_four**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_four**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_four**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"

Expected result

Server side should be showing all the divisions:

{ sms: { division: '**division_one**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_two**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_three**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"
{ sms: { division: '**division_four**' } }
::ffff:127.0.0.1 - - [29/Jan/2019:13:24:02 +0000] "POST /inbound HTTP/1.1" 200 36 "-" "axios/0.18.0"

Upvotes: 1

Views: 43

Answers (2)

Bernie
Bernie

Reputation: 5055

The variable sms is an Object and you're working on the reference inside the map function. Also it's necessary to return the post call Promise.

    Promise
    .all([
          'division_one',
          'division_two',
          'division_three',
          'division_four'
         ].map(function(division) {
           return axios.post('http://localhost:3000/inbound', {
              division: division,
           }
        );

    }))
    .then(function(results) {

    })

Upvotes: 2

Dracks
Dracks

Reputation: 107

Try to define sms in promise

Promise.all(['division_one','division_two','division_three','division_four'].map(function(division) {
let sms = {};

sms.division = division;

console.log(sms);

axios.post('http://localhost:3000/inbound', {
    sms
})
    .then(function (response) {
        return response;
    });

})).then(function(results) {
})

Upvotes: 0

Related Questions