用“绞线”一词指的是在其中执行一系列JS命令的“线程”。但是据我了解,这些并不是真正的“线程”,因为(浏览器)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
完成后,是否有更好的方法在原始“链”中获取相同的数据?
混合手动.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
}