Using fetch in Javascript to retrieve orders list

I'm trying to execute the following Javascsript code:

if(platform == 'bo'){
fetch(brickowlUrl)
.then(response => response.json())
.then(data => console.log(data))
.then(data => obj = data);
};

The code works up until the last line. The data displays on my terminal, but after that it treats data as undefined or void.

Can anyone tell me why this is happening? I have tried using an async function for this, but I get the same result.

Perhaps it's the format the data is returned in? TIA.

Comments

  • 3 Comments sorted by Votes Date Added
  • data goes out of scope with the closing curly bracket.
  • Mac,

    Thanks. Yes, but the var obj is declared outside of the brackets. I've also tried sending data directly to a function within the curly brackets and still no joy.
  • Okay. Found a snippet of code that I adapted to my needs and it worked. Just in case anyone else might need it:

    fetch(brickowlUrl)
    .then(response => {
    if (!response.ok) {
    throw new Error('Network response was not ok');
    }
    return response.json();
    })
    .then(data => {
    // Store the fetched data in an object
    const boObj = data;

    // Do something with the data
    console.log(boObj);
    toCSV(boObj, platform, reqType)
    })
    .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
    });
Sign In or Register to comment.