0

By the word "strand" I'm referring to the "thread" in which a sequence of JS commands is executed. But as far as I understand it these aren't really "threads", since there is only one thread in (browser) JS.

With this:

async function postData(url = '', data = {}) {
  const response = await fetch(url, {
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    credentials: 'same-origin',
    headers: {
      'Content-Type': 'application/json'
    },
    redirect: 'follow', 
    referrerPolicy: 'no-referrer', 
    body: JSON.stringify(data) 
  });
  return response;
}

... and then this:

(async function(){

    // let deliveredData

    // launch a time-consuming call:
    const resultOfPostData = postData( 'ajaxProcessor_jq.cgi', { table: 'contacts' })
    .then( response => {
        console.log( 'response' )
        console.log( response ) // class Response
        console.log( `response.status ${response.status}`      )
        if( response.status == 200 ){
            data = response.json();
            console.log( 'data' );
            console.log(data); // this is a Promise... state "pending"
            return data
        }
        throw `bad return status: ${response.status}`
    })
    .then( data => {
        // now the "payload" has been delivered in this "strand"
        // deliveredData = data
        console.log( data ); // JSON data parsed by `response.json()` call
    })
    .catch(( err ) => {
        console.log( 'err' );
        console.log( err );
    });

    console.log( 'resultOfPostData' )
    console.log( resultOfPostData ) // Promise with state "pending"

    await resultOfPostData

    console.log( 'resultOfPostData after await:' )
    console.log( resultOfPostData ) // Promise with state "fulfilled"

    // can I get the result of the Promise here?
    // console.log( 'deliveredData:' )
    // console.log( deliveredData )

})()

The second then, where the payload JSON data is delivered, is obviously somewhere where you can do something with that data.

One way of getting the payload data in the calling strand is by the method you can see if you uncomment all the lines containing deliveredData. But this looks clunky.

Is there a better way of obtaining that same data in the original "strand" after await has completed?

mike rodent
  • 14,126
  • 11
  • 103
  • 157
  • FYI Javascript is single-threaded. You're talking about synchronicity here, not threading – Liam May 20 '20 at 11:51
  • 1
    [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 20 '20 at 11:52
  • 1
    All you need is already in your script. You're just missing a `return` – Andreas May 20 '20 at 11:52
  • 2
    I'd also suggest you either use `async`/`await` or `promise.then()` mixing them up is just confusing – Liam May 20 '20 at 11:55
  • If you replace "strand" with *promise chain* or *chain of tasks*, this is actually quite accurate. – Jonas Wilms May 20 '20 at 11:58

1 Answers1

1

It rarely makes sense to mix manual .then chaining and await (as they do basically the same thing under the hood). Your code can be written as:

try { 
  const res = await postData( 'ajaxProcessor_jq.cgi', { table: 'contacts' });
  if(!res.ok) {
    // handle status code
  }
  const result = await res.json();
  // do stuff with result
} catch {
  // handle error occured while fetching / parsing
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151