0

I am trying to work with the Marvel api and using multiple sources of data with an axios.get method. I am at the moment returning with the characters ID to display the characters info and the comics associated with them. I made a function to get the comics using another axios.get which I am trying to assign to a variable so I can pass that to my template engine. I consoled the variable and got [object Promise], when I pass to my engine nothing appears. I am unsure what I am doing wrong and using then() and catch() is kinda confusing me even when I read the documentation.

function getCharactersComic(character){
var charactersComics;
return axios.get('https://gateway.marvel.com:443/v1/public/characters/' + character[0].id + '/comics?limit=10', {
  params:{
    ts:  timeStamp,
    apikey: marvelKey.pubKey,
    hash:  marvelHash
  }
})
.then(response =>{
  charactersComics = response.data.data.results;
  console.log("comics" + charactersComics);
   return charactersComics; 
})
.catch(err => {
  console.log('This is the error from comics: ', err.response);
})


    router.get("/:id", function(req,res){
  axios.get('https://gateway.marvel.com:443/v1/public/characters/' + req.params.id,{
    params: {
      ts:  timeStamp,
      apikey: marvelKey.pubKey,
      hash:  marvelHash
    }
  })
  .then(response =>{
    let character = response.data.data.results;
    let comics = getCharactersComic(character);
    console.log('inside call ' + comics);
    res.render('character', {character: character , comics:comics});
  })
  .catch(error => console.log('This is the error from id: ', error));
});
  • `getCharactersComic()` returns a Promise that *resolves* to `comics`, which you can access via another chained `then()`. – Roamer-1888 Jan 03 '20 at 19:28
  • And don't forget to return that inner Promise, ie `return getCharactersComic(character).then(comics => .....);` – Roamer-1888 Jan 03 '20 at 19:30
  • Doing the return to the getCharactersComic() inside the .then() would that still allow me access to the initial response data? I saw some confusing ways of returning objects with each information added to the object? – Jason Glenn Jan 03 '20 at 22:40
  • Yes, `response` will still be in scope providing you form an inner (nested) chain. The whole issue of accessing previous promise results is comprehensively discussed [here](https://stackoverflow.com/q/28250680/3478010); my suggestion is covered by the answer "Nesting (and) Closures". As you will see, other approaches are possible. – Roamer-1888 Jan 04 '20 at 04:29

0 Answers0