Tuesday, 4 April 2017

Access value that promise .then returns outside of promise

Title says it all, I am using the async-library eachSeries method

var asyncEachSeries = require('async/eachSeries');

const getContent = function (item) {
  contentResponse = fetchContent(item);
  return contentResponse;
}

if (recommendationsArr.length > 0) {
  asyncEachSeries(recommendationsArr, function (item, callback) {
    getApiContent(item).then(function getValidResult(response) {
      try { // to get audio
        valueOne = response.content.valueOne || null; //may or may not be present
        recommendationsArr.splice(recommendationsArr.indexOf(item), 1); 
        validItem = item;
        console.log("##### valueOne is: ", valueOne); // I get data here
        return true;
      } catch (err) {
        valueOne = null;
        return false;
      }
    });
    //I am guessing I need a return statement here, though not sure what
  });

  // Access valueOne, validItem, recommendationsArr here and do something
  console.log("##### Outside promise, valueOne is: ", valueOne); // no data here
}

I need to be able to access the values set in try block outside of the asyncEachSeries iteration loop. I understand I will have to return the processed/new values but am not sure at what point and how to return those values.



via user988544

No comments:

Post a Comment