如何在 JavaScript 中訪問非同步函式 async() 返回的結果中的物件屬性?
在本文中,您將瞭解如何從 JavaScript 中 async() 函式返回的結果中訪問物件屬性。JavaScript 中的物件屬性是與物件本身關聯的變數,即屬性具有名稱,並且值是與屬性連結的屬性之一。
示例 1
在本例中,讓我們瞭解如何使用點表示法訪問物件屬性。
console.log("A function is created that returns promise object") const promiseFunction = (input) => { return new Promise((resolve, reject) => { return resolve({ val: input }) }) } console.log("
Calling the function using dot notation") async function test() { const result = await promiseFunction("This is an asynchronous function response") console.log(result.val); } test();
解釋
步驟 1 - 定義一個返回 promise 的函式 'promiseFunction'。
步驟 2 - 定義一個非同步函式 'test',使用點表示法訪問物件的屬性。
步驟 3 - 顯示結果。
示例 2
在本例中,
console.log("A function is created that returns promise object") const promiseFunction = (input) => { return new Promise((resolve, reject) => { return resolve({ val: input }) }) } console.log("
Calling the function using bracket notation") async function test() { const result = await promiseFunction("This is an asynchronous function response") console.log(result["val"]) } test();
解釋
步驟 1 - 定義一個返回 promise 的函式 'promiseFunction'。
步驟 2 - 定義一個非同步函式 'test',使用方括號表示法訪問物件的屬性。
步驟 3 - 顯示結果。
廣告