0

Is (3) a correct way of using then()? I don't need the Promise returned by fetch(), I just want obtain an updated array of emails once fetch() is done.

Are my comments for (1) (2) and (3) correct? I tested them by running another then() (4) after each of them, and they seem right. I just want to be sure.

function setArchive(email_id, boolArchive) {
  fetch(`/emails/${email_id}`, {
    method: 'PUT',
    body: JSON.stringify({
      archived: boolArchive
    })
  })

   ##### (Using just one of these at a time)

  (1) .then(load_mailbox('inbox'))               // doesn't wait for fetch() to resolve, returned Promise accessible by the next then()
  (2) .then((response) => load_mailbox('inbox')) // waits for fetch(), returned Promise NOT accessible by the next then() (4)
  (3) .then(() => load_mailbox('inbox'))         // waits for fetch(), returned Promise NOT accessible by the next then() (4)

   #####

  (4) .then(response => console.log(response)) // (2) and (3) logs 'undefined'


Thanks for your help.

rickyc
  • 57
  • 7
  • What does "*returned Promise accessible by the next then()*" and "*returned Promise NOT accessible by the next then()*" mean? – VLAZ Mar 23 '21 at 19:23
  • This thread answered my question. Thanks all! https://stackoverflow.com/q/50836242/12001706 – rickyc Mar 25 '21 at 06:31

1 Answers1

1

Ok, I think you are saying that you want to do something conditional.

i.e. you want to do one of three things when the fetch completes?

I recommend you have a fetch that takes optional.

In the demo below we accept a url and an Array of functions to execute once the fetch is complete. In the way we could pass different functions to the method when we are looking to do different tasks. I mixed up sync and async just for demonstration.

// Lets have three methods
const postFetchOne = async (json) => {
  console.log(JSON.stringify(json));
};

const postFetchTwo = (json) => {
  document.querySelector('pre').innerHTML = JSON.stringify(json, 3);
};

const doSomethingDifferent = async (json) => {
  console.log(`Received JSON - Length ${JSON.stringify(json).length}`);
};

// Now our actual fetch
const goGetJSON = async (url, funcs) => {
  const todo = Array.isArray(funcs) ? funcs : [funcs];
  
  const json = await (await fetch(url)).json();
  
  // Now run each function
  todo.forEach(f => f(json));
};

const testURL = 'https://jsonplaceholder.typicode.com/todos/1';
goGetJSON(testURL,
          [postFetchOne, postFetchTwo]);
          
// lets do something different
goGetJSON(testURL, doSomethingDifferent);
<pre></pre>
Bibberty
  • 4,670
  • 2
  • 8
  • 23