Skip to content Skip to sidebar Skip to footer

Why Is No Value Returned From My Promise?

In this slightly reduced code, one or more weeks of observations are downloaded a week at a time from an API, and aggregated into rows and exported to CSV. At least that is the ide

Solution 1:

A promise is not a magical object that "becomes" a different value when it is resolved. When you were doing rows.push(promiseArray[i]);, you were collecting promise objects not the results that they contained.

To access the result that a promise was or will be fulfilled with, you need to chain a .then(…) callback to it in which you can access the result as the parameter. To collect the results from all the promises in the array, you use Promise.all, which returns another promise that not only waits for all the input promises but also fulfills with an array of their result values.

$("#downloadBtn").click(function() {
    var weeks = getWeeks(startDate.val(), endDate.val());
    // start downloading the datavar promiseArray = weeks.map(function(week) { // map is simpler than a loop with `push`returnfetchDataWeek( week[0], week[1] );
    })
    Promise.all(promiseArray).then( function(results) { // Wait for all promises to resolvevar rows = [headers].concat(results);
        exportToCsv( fileName, rows );
    })
});

functionfetchDataWeek( startDay, endDay, _promise ) {
    var url = "https://api" + startDay + endDay + ".json";
    var jQpromise = $.ajax({
        url: url
    });
    var qPromise = Q(jQpromise);
    return qPromise.then(parseHistory);
}

functionparseHistory(data) {
    var weekRows = [];
    var days = data.history.days;
    for (var i = 0; i < days.length; i++) {
        var dayRows = formatDay( days[i] );
        for (var j= 0; j < dayRows.length; j++) {
            weekRows.push(dayRows[j]);
        }
    }
    return weekRows;
}

Solution 2:

You can receive the result of your promises in the then handler:

Promise.all(promiseArray).then( function (results) { // Wait for all promises to resolvevar rows = [headers].concat(results);
    exportToCsv( fileName, rows );
  })

Post a Comment for "Why Is No Value Returned From My Promise?"