2016-07-08 5 views
2

Ich versuche zu sehen, wie man mit gleichzeitig asynchronen Anfragen in Javascript arbeiten, wissen Sie eine Möglichkeit mit Axios, die Ergebnisse der erfolgreichen Anfragen zu erhalten, selbst wenn man scheitert? Wenn nicht, wie würden Sie mit dieser Situation umgehen?axios gleichzeitige Anfragen: eine Möglichkeit, die Ergebnisse von den erfolgreichen Anfragen zu erhalten, auch wenn einige fehlgeschlagen sind?

var axios = require('axios') 

var options = [{ 
     baseURL: 'https://some-base-url' 
    , url: '/some-path&key=some-key' 
    , method: 'post' 
    , data: 'some-data' 
}, { 
     baseURL: 'https://some-base-url' 
    , url: '/some-path&key=some-key' 
    , method: 'post' 
    , data: 'some-other-data' 
}, { 
     baseURL: 'https://some-base-url' 
    , url: '/some-path&key=WRONG-KEY' // WRONG KEY 
    , method: 'post' 
    , data: 'some-other-data' 
}] 

axios.all([ 
     axios.request(options[ 0 ]) 
    , axios.request(options[ 1 ]) 
    , axios.request(options[ 2 ]) 
]).then(axios.spread(function (res1, res2, res3) { 
    // when all requests successful 
})) 
.catch(function(res) { 
    // third request was unsuccessful (403) but no way to get 
    // the results of the two previous successful ones? 
    console.log(res) 
}) 

Antwort

2

einen .catch Block für die "optional" Anfrage hinzufügen

axios.all([ 
     axios.request(options[ 0 ]) 
    , axios.request(options[ 1 ]) 
    , axios.request(options[ 2 ]).catch(function() { return false}) 
]).then(axios.spread(function (res1, res2, res3) { 
    console.log(res1) //Respone of options[0] 
    console.log(res2) //Response of options[1] 
    console.log(res3) //False (When options[2] fails) 
})) 
Verwandte Themen