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?
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
}