[翻译] Javascript: 如何访问Promise对象返回值

在Javascript中,什么是Promise

Promise是一个对象,表示一个异步操作的事件完成或失败。

Promise对象可以是如下状态:

  • pending
  • fulfilled
  • rejected

最广泛使用的异步操作的一个实例是Fetch API。fetch() 方法返回一个Promise对象。

如果我们从后端API获取一些数据。对于这篇博文,我将使用JSONPlaceholder – 一个伪造的REST API。我们将获取一个id=1的用户数据。

fetch("https://jsonplaceholder.typicode.com/users/1")

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

1- then() 链式操作

它是最简单和最明显的方式。

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

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

结果如下:

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

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

但是如果我们想要在之后的代码中使用返回值,怎么办?

如果我们尝试像这样做(错误方式!

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

console.log(address);

我们将得到

Promise { <pending> }

得到这种结果,是因为Javascript代码总是同步执行,所以console.log()函数在fetch()请求后立即开始,而没有等待直到它解析完成。当console.log()函数开始运行的时刻,fetch()请求函数返回的Promise对象处于pending状态。

那就是说,我们可以访问另一个 .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();

或使用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();

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

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

结论

Promise对象广泛用于Javascript异步编程。而且开发者对于如何正确使用它,有时还有些困惑。在这篇博客文章里,我已经试图描述一个用户例子,即当开发者需要在之后的代码中使用来自Promise对象的返回值的实例。 

 

英文原文链接:https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck

 

更多中文参考资料

[1] JavaScript Promise - Javascript教程. https://www.runoob.com/js/js-promise.html

[2] JavaScript Promise 对象 – 编程技术. https://www.runoob.com/w3cnote/javascript-promise-object.html

[3] 7.6 Promise – 7. 浏览器 – JAVASCRIPT教程- 廖雪峰的官方网站. https://liaoxuefeng.com/books/javascript/browser/promise/index.html

 

posted @ 2025-03-11 08:14  klchang  阅读(350)  评论(0)    收藏  举报