我正在使用 try/catch 發出一些獲取請求,然后我從 HTML 中提取標題并將其添加到我的物件“sleekResponse”當我嘗試決議正文并將其添加到該物件時我遇到了問題回傳值不包括我從 HTML 中提取的標題
我知道這與異步性或我對 Promises 的淺薄理解有關,但我不知道為什么回傳值與它在發送之前記錄的值不同。
async function fetchUrl(url) {
console.log(url);
try {
const myInit = {
mode: 'cors'
}
let sleekResponse = {};
await fetch(url, myInit).then(function (response) {
sleekResponse.redirected = response.redirected;
sleekResponse.status = response.status;
return response;
})
.then((response) => titleWait(response))
.then((res) => sleekResponse.title = res)
function titleWait(response) {
Promise.resolve(response.text()).then((res) => {
a = res.split('<title>');
b = a[1].split('</title>')
sleekResponse.title = b[0];
return sleekResponse;
})
console.log(sleekResponse);
return sleekResponse;
}
console.log(sleekResponse); // This logs the correct value
return sleekResponse; // when it's returned it doesn't show the title that was added
} catch (err) {
return `${err}`;
}
}
我嘗試了很多事情,我不記得我嘗試過的所有事情。我知道我遺漏了一些可能很明顯的東西,但我仍然不明白為什么 console.log 值與后面一行回傳的值不同。
uj5u.com熱心網友回復:
主要問題是它titleWait不會回傳自己的承諾:
function titleWait(response) {
return Promise.resolve(response.text()).then((res) => {
a = res.split('<title>');
b = a[1].split('</title>')
sleekResponse.title = b[0];
return sleekResponse;
});
}
這仍然是一種非常復雜的撰寫方式。這個更好:
async function titleWait(response) {
const res = await response.text());
const a = res.split('<title>');
const b = a[1].split('</title>')
sleekResponse.title = b[0];
return sleekResponse;
}
uj5u.com熱心網友回復:
我希望我能幫上忙
這個基本的 fetch();
const response = await fetch('your url')
const data = await response.json();
console.log(data);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453713.html
標籤:javascript 异步 异步等待 承诺 拿来
上一篇:如何在NodeJS中等待函式執行
下一篇:useEffect中的異步處理
