問題是底部函式無法提取 xmlhttprequest 的結果。對如何為此添加承諾感到困惑
我是否必須使用 aysnc 和 await,或者我如何才能在請求后獲得函式的結果?
我已經測驗了在 weatherPull 函式中呼叫 degreesInner 控制臺日志記錄,它回傳了正確的值。看起來 kaminoan 函式沒有等待 weatherPull 函式完成請求并記錄未定義
uj5u.com熱心網友回復:
只需將回傳結果包裝在一個 promise 中,并使用 promise resolve 和 reject 函式來回傳結果或錯誤:
function weatherPull () {
return new Promise((resolve, reject) => GM_xmlhttpRequest({
method: 'GET',
url: 'https://weather.com/weather/today/l/97a4d5b4ba6364679573ce81d1f6ae73791fab877b50c3433657376f8b676c27',
onload: function (pull) {
const fetch = new DOMParser();
const html = fetch.parseFromString(pull.responseText, 'text/html');
const degree = html.querySelector('#WxuCurrentConditions-main-eb4b02cb-917b-45ec-97ec-d4eb947f6b6a > div > section > div > div.CurrentConditions--body--l_4-Z > div.CurrentConditions--columns--30npQ > div.CurrentConditions--primary--2DOqs > span');
resolve(degree.innerHTML);
},
onerror: reject
}));
}
然后,您可以使用 promise “then” 函式訪問資料,或者如果拋出錯誤,則使用 promise catch 函式捕獲它:
function kaminoan () {
weatherPull()
.then((data) => console.log('this is your data', data))
.catch((error) => console.log('failed to fetch data', error));
}
如果您想以異步等待方式執行此操作,則以下方法是等效的:
async function kaminoan () {
try {
const data = await weatherPull();
console.log('this is your data', data);
} catch (error) {
console.log('failed to fetch data', error);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537067.html
標籤:javascript异步异步等待xmlhttp请求篡改猴子
