Search code examples
javascriptecmascript-6fetches6-promise

Getting undefined values in fulfilled promises


I am getting undefined values for fulfilled promises:

0: {status: "fulfilled", value: undefined}
1: {status: "fulfilled", value: undefined}
2: {status: "fulfilled", value: undefined}
3: {status: "rejected", reason: TypeError: Failed to fetch}
4: {status: "rejected", reason: TypeError: Failed to fetch}
5: {status: "rejected", reason: TypeError: Failed to fetch}

How can I get the data in value properties of the fulfilled promises?

EDIT: I added the return dataObj statements, but to no avail.

var fetchArr = [];

var url1 = "url1";
fetchArr.push(fetch(url1).then(
    response => {
        response.json().then(function(data) {
            var dataObj = {};
            dataObj.playlistNumber = i;
            dataObj.data = data;

            return dataObj;
        });
    }
));

var url2 = "url2";
fetchArr.push(fetch(url2).then(
    response => {
        response.json().then(function(data) {
            var dataObj = {};
            dataObj.playlistNumber = i;
            dataObj.data = data;

            return dataObj;
        });
    }
));

var url3 = "url3"
fetchArr.push(fetch(url3).then(
    response => {
        response.json().then(function(data) {
            var dataObj = {};
            dataObj.playlistNumber = i;
            dataObj.data = data;

            return dataObj;
        });
    }
));


Promise.allSettled(fetchArr).then(function(dataArr) {
    console.log(dataArr);
});


// Polyfill for Promise.allSettled
if (!Promise.allSettled) {
    const rejectHandler = reason => ({ status: "rejected", reason });
    const resolveHandler = value => ({ status: "fulfilled", value });

    Promise.allSettled = function(promises) {
        const convertedPromises = promises.map(p => Promise.resolve(p).then(resolveHandler, rejectHandler));
        return Promise.all(convertedPromises);
    };
}

Solution

  • In your callback of the first then call you dont return anything:

    fetchArr.push(fetch(url1).then(
        response => {
            // There is no return here 
            response.json().then(function(data) {
                var dataObj = {};
                dataObj.playlistNumber = i;
                dataObj.data = data;
    
                return dataObj;
            });
        }
    ));
    

    so it would work if you did this:

    fetchArr.push(
        fetch(url1).then(response => {
            // return here
            return response.json().then(function(data) {
                var dataObj = {};
                dataObj.playlistNumber = i;
                dataObj.data = data;
    
                return dataObj;
            })
        })
    );
        
    

    More on chained Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#chained_promises