0

I try to return a list from a 2-layered "then". I can successfully return the data from the "inner then" (by chaining another "then") but I cannot figure out how to get outside of the "second then".

Here is my code with some comments to make my problem more understandable.

let emptyList; //Empty variable

function getList() {
        return getOrderList() // Return the payload to call the fetch
        .then(
            function(payload) {
                   //The function standardFetchCall countains the fetch and return the successful result of the call
                   standardFetchCall(payload).then((data) => {  
                      emptyList = data;
                      console.log(emptyList); // Successfully log the list
                      return emptyList;
                   })
                //If I do a then here to log the emptyList, it works. But to get it more readable, I would like to have it at least outside of the second "then"
            }
        )
}

//I don't know if I need to call a function which wrap the above or if there is any way to chain the call after the first "then"
getList()
.then(
    function(emptyList) { //The content of the variable here is called too fast and is empty (undefined)
        console.log(emptyList);
    }
);
Max
  • 95
  • 2
  • 11
  • 1
    You might only be missing a `return` in `function(payload)`. That function currently returns nothing but maybe you want it to return a promise? – Matt Thomas Sep 21 '22 at 20:29
  • 1
    Thank you, I solved it by adding a ```return``` at the beginning of the ```standardFetchCall(payload)``` line. – Max Sep 21 '22 at 20:35
  • FWIW you can simplify this a lot by just doing `return getOrderList().then(standardFetchCall);` (assuming you don't need the `console.log` call). The global/shared `emptyList` variable is unnecessary. – Felix Kling Sep 21 '22 at 23:41

0 Answers0