在同一个JS中获取一个fetch的结果"strand"?

Get the result of a fetch in the same JS "strand"?

"strand" 这个词指的是 "thread",其中执行了一系列 JS 命令。但据我了解,这些并不是真正的 "threads",因为(浏览器)JS 中只有一个线程。

有了这个:

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

...然后是这个:

(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 )

})()

第二个 then,其中传输有效负载 JSON 数据,显然是您可以对该数据执行某些操作的地方。

在调用链中获取有效负载数据的一种方法是通过取消注释包含 deliveredData 的所有行时可以看到的方法。但这看起来很笨重。

await 完成后,是否有更好的方法在原始 "strand" 中获取相同的数据?

混合手动 .then 链接和 await 很少有意义(因为它们在幕后做的事情基本相同)。你的代码可以写成:

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
}