Javascript:如何访问 Promise 对象的返回值

2025-06-07

Javascript:如何访问 Promise 对象的返回值

最初发表在我的个人博客上。

简介(完全离题)

距离我上次发博文已经过去快三个月了。这是有原因的。

首先,尽管采取了所有预防措施,我还是于2020年6月下旬感染了冠状病毒(COVID-19)。接下来的两周简直是地狱。我的身体状况非常糟糕,只能躺在床上,祈祷着病情能尽快好转。之后,我又恢复了两三周。现在我终于恢复了正常生活,甚至恢复了健身训练。所以,冠状病毒可不是闹着玩的。请大家注意安全。

其次,我的祖国——白俄罗斯——正在发生许多事情。白俄罗斯人民正在与独裁统治作斗争。我们的(前)总统在2020年8月9日举行的上次选举中落败,但他继续掌权,使用残暴的警察和军队对付和平的民众,并威胁任何反对他的人。但我们每天都在继续抗争和抗议。我非常重视所有这些事件,并希望有一天醒来,看到一个自由、民主、繁荣的白俄罗斯。

现在回到主题。

Javascript 中的 Promise 是什么

Promise是一个代表异步操作最终完成或失败的对象。

Promise 可能处于以下状态之一:

  • 待办的
  • 已实现
  • 拒绝

JavaScript 中最广泛使用的异步操作示例之一是Fetch API。fetch() 方法返回一个 Promise。

假设我们从后端 API 获取一些数据。在本文中,我将使用JSONPlaceholder(一个模拟的 REST API)。我们将获取 id = 1 的用户数据:

fetch("https://jsonplaceholder.typicode.com/users/1")
Enter fullscreen mode Exit fullscreen mode

让我们看看如何访问返回的数据。

1 - .then() 链式调用

这是最简单、最明显的方法。

fetch("https://jsonplaceholder.typicode.com/users/1") //1
  .then((response) => response.json()) //2
  .then((user) => {
    console.log(user.address); //3
  });
Enter fullscreen mode Exit fullscreen mode

在这里我们(1)从 API 获取数据,(2)将其转换为 JSON 对象,然后(3)将用户的地址值打印到控制台。

结果是:

{
  street: 'Kulas Light',
  suite: 'Apt. 556',
  city: 'Gwenborough',
  zipcode: '92998-3874',
  geo: { lat: '-37.3159', lng: '81.1496' }
}
Enter fullscreen mode Exit fullscreen mode

2 - 稍后在代码中使用返回值

但是如果我们想在代码的后面某处使用返回的值怎么办?

如果我们尝试这样做(错误的方式!):

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

console.log(address);
Enter fullscreen mode Exit fullscreen mode

我们将得到

Promise { <pending> }
Enter fullscreen mode Exit fullscreen mode

发生这种情况是因为 JavaScript 代码始终是同步执行的,因此 console.log() 函数会在 fetch() 请求之后立即启动,而不是等到它被解析之后。在 console.log() 函数开始运行的那一刻,fetch() 请求应该返回的 Promise 处于待处理状态。

也就是说,我们可以在另一个 .then() 回调中访问 Promise 对象的返回值:

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

const printAddress = () => {
  address.then((a) => {
    console.log(a);
  });
};

printAddress();
Enter fullscreen mode Exit fullscreen mode

或者使用 async / await 语法:

const address = fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => {
    return user.address;
  });

const printAddress = async () => {
  const a = await address;
  console.log(a);
};

printAddress();
Enter fullscreen mode Exit fullscreen mode

通过这两种方式,我们将得到:

{
  street: 'Kulas Light',
  suite: 'Apt. 556',
  city: 'Gwenborough',
  zipcode: '92998-3874',
  geo: { lat: '-37.3159', lng: '81.1496' }
}
Enter fullscreen mode Exit fullscreen mode

结论

Promise 对象在 JavaScript 异步编程中被广泛使用。有时,开发人员会困惑如何正确使用它。在这篇博文中,我尝试描述一个用例,即开发人员需要在代码的后续部分使用 Promise 对象的返回值。

文章来源:https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck
PREV
让您的网站在 Twitter、Facebook 等社交媒体平台上支持卡片式显示?Open Graph 元标签在哪里?卡片图像最佳实践:我如何知道它有效?
NEXT
100天编程与Scrum:新的挑战