[英]Await fetch returns a promise, not the data
我正在從電子表格中獲取和處理數據,如下所示:
const getJsonSheet = async () => {
const response = await fetch('<FETCH-SPECIFIC-SPREADSHEET-LINK>');
const data = await response.json();
let cells = await data.feed.entry;
let table = {
massa:[],
description:[],
price:[],
imgLink:[]
};
await cells.map( cell => {
if ( parseInt(cell.gs$cell.row) > 1) {
let rowValue = parseInt(cell.gs$cell.row) - 2;
let inputValue = cell.gs$cell.inputValue;
switch (cell.gs$cell.col) {
case "1":
table.massa[rowValue] = inputValue;
break;
case "2":
table.description[rowValue] = inputValue;
break;
case "3":
table.price[rowValue] = inputValue;
break;
case "4":
table.imgLink[rowValue] = inputValue;
break;
default:
console.log('Cell out of range.')
}
}
})
return table;
};
export default getJsonSheet;
我在另一個文件中導入並執行 getJsonSheet(),將它的值分配給一個變量,然后我 console.log 這個變量。 我希望將表 object 登錄到控制台,但實際上記錄了 Promise。 但是,此記錄的 promise 已滿,並且結果為“表” object。 我還沒有完全理解 Promises、async 和 await - 我是這個特定主題的新手。
有沒有辦法讓“表”object 直接分配給一個變量,這樣我就可以在其他地方使用它來操作 DOM?
PS:數據被正確獲取,因為我想要的只是承諾的結果。 我的問題是將承諾的結果分配給一個變量。
看看下面的例子:
async function f3() {
const y = await 20;
return 5;
}
console.log(f3());
印刷:
Promise {<pending>}
但是這個:
async function f3() {
const y = await 20;
return 5;
}
console.log(await f3());
印刷:
5
如果您希望返回5
,則您的console.log
需要位於執行堆棧頂層或另一個異步 function 中,如下所示:
async function f3() {
const y = await 20;
return 5;
}
async function f_another() {
return await f3();
}
由於異步 function 將以異步方式運行,因此您將始終獲得同步結果(Promise obj)。 正確用法是:
async function test()
{
return 'hello async';
}
//call it
test().then(res){console.log(res)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.