JavaScript 如何异步函数返回的结果中访问对象属性
在本文中,我们将看到如何从JavaScript中异步函数返回的javascript对象结果中访问属性。
javascript对象属性是与对象本身关联的变量,即属性具有名称,值是与属性链接的属性之一,定义了对属性的访问权限。您可以使用点(.)表示法或方括号([])表示法访问对象的属性。例如,键是obj对象的属性,并且可以使用点表示法和方括号表示法来访问属性的值。
var obj = {"key": "value"}
console.log(obj.key) // dot notation
console.log(obj["key"]) // bracket notation
输出:
value
value
在这里,我们将了解如何访问 promise 对象的响应。一个 Promise 是一个 JavaScript 对象,它在异步操作完成后返回。Promise 有 3 种状态:
- Fulfilled: 异步操作完成时没有抛出任何错误。
- Rejected: 异步操作无法完成并在中途抛出错误。
- Pending: 异步操作正在进行中。
现在,为了了解如何在对象是 Promise 的响应时访问 JavaScript 对象的属性,让我们看一下以下方法。
方法1:使用 async/await 语法处理基于 promise 的行为
async/await 可以帮助我们编写更清晰的代码来处理 Promise。async 关键字用于处理异步操作的函数,而 await 关键字用于在 async 函数中等待异步操作的响应,例如一个 promise。
示例: 这个示例描述了在 JavaScript 中访问对象属性的过程。
JavaScript
<script>
// A function that returns a promise object
const call = (input) => {
return new Promise((resolve, reject) => {
return resolve({
val: input
})
})
}
// Let’s await the response of the promise
// and log the result to the console
async function test() {
const res = await call("Hello World!")
console.log(res.val); // dot notation
console.log(res["val"]) // bracket notation
}
test();
</script>
如果你不想使用 await 关键字来等待Promise的响应,那么你也可以选择使用Promise链技术,使用 then 关键字在回调链中等待Promise的响应后再继续向前进行。
输出:
Hello World!
Hello World!
方法2: 使用“then”关键字实现promise链
then()方法处理promise的响应,当promise状态为fulfilled或rejected时。它接受两个回调函数,分别处理上述两种状态。
示例: 这个示例描述了在Javascript中使用“then”关键字实现promise链来访问对象的属性的过程。
Javascript
<script>
// A function that returns a promise object
const call = (input) => {
return new Promise((resolve, reject) => {
return resolve({
val: input,
});
});
};
// Use then keyword to wait for the response
// and use a callback function to log the
// result to the console
// Dot notation
call("Hello World!")
.then((res) => console.log(res.val));
// Bracket notation
call("Hello World!")
.then((res) => console.log(res["val"]));
</script>
输出:
Hello World!
Hello World!