Javascript承诺和地图功能

时间:2019-01-29 13:27:23

标签: node.js

我试图遍历一个数组并发送值在服务器端。问题是服务器端每次都返回相同的结果。

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) {

})

客户端结果:

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

服务器端结果:

{ 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"

预期结果

服务器端应显示所有分区:

{ 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"

2 个答案:

答案 0 :(得分:2)

变量sms是一个对象,您正在map函数内部的引用上工作。同样,有必要返回帖子调用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) {

    })

答案 1 :(得分:0)

尝试在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) {
})