迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中如何访问 Promise 的值

作者:迹忆客 最近更新:2022/12/02 浏览次数:

使用 Promise.then() 方法访问承诺的值,例如 p.then(value => console.log(value))then() 方法接受一个函数,该函数将 promise 的解析值作为参数传递。

// 👇️ Example promise
const p = Promise.resolve('hello');

p.then(value => {
  console.log(value); // 👉️ "hello"
}).catch(err => {
  console.l

我们使用 Promise.resolve() 方法来获取示例承诺。

为了解决 promise,我们调用了 Promise 对象的 then() 方法。

我们传递给 then() 方法的函数以解析值作为参数被调用。 我们可以在函数体中访问这个值。

请注意 ,我们还使用了 catch() 方法。

这是因为一个 promise 可以有 3 个状态:

  1. pending - 初始状态,既没有完成也没有被拒绝。
  2. fulfilled - 操作成功并且承诺得到解决。
  3. rejected - 操作失败。

如果 romise 得到满足并且操作成功,我们传递给 then 方法的函数将被调用。

如果 promise 被拒绝,我们可以在 catch() 方法中访问拒绝的原因(错误)。

// 👇️ Example rejected promise
const p = Promise.reject('Something went wrong');

p.then(value => {
  console.log(value);
}).catch(err => {
  console.log(err); // 👉️ "Something went wrong"
});

我们使用 Promise.reject 方法来获得被拒绝的承诺。

这一次,我们的 catch 方法被调用并传递了拒绝的原因。

从传递给 then() 方法的函数返回的值被包装在一个承诺中,因此我们可以根据需要链接对该方法的多次调用。

const p = Promise.resolve(13);

p.then(value => {
  console.log(value); // 👉️ 13

  return value + value;
}).then(value => {
  console.log(value); // 👉️ 26

  return value + value;
});

如果我们不从回调函数返回值,将隐式返回 undefined,它被包装在一个 promise 中并由 then() 方法返回。

或者,我们可以使用 async/await 语法访问承诺的值。

要访问承诺的值:

  1. 定义一个异步函数。
  2. 使用 await 运算符等待承诺。
  3. 将使用 await 运算符的结果分配给变量。
// 👇️ Example promise
const p = Promise.resolve('Hello World');

async function example() {
  try {
    const value = await p;
    console.log(value); // 👉️ "Hello World"
  } catch (err) {
    console.log(err);
  }
}

example();

我们能够使用 await 运算符,因为我们将函数标记为异步。

await 运算符用于等待 Promise 被执行或拒绝。

一种简单的思考方式是——当使用 await 运算符时,我们在特定函数中的代码将停止在使用 await 的行上,直到承诺被履行或拒绝。

与使用 then() 方法相比,这使我们的代码更易于阅读。

请注意 ,我们将操作包装在 try/catch 块中。

这是因为,如果 Promise 被拒绝,我们希望能够在我们的 catch 块中访问原因。

// 👇️ Example rejected promise
const p = Promise.reject('Something went wrong');

async function example() {
  try {
    const value = await p;
    console.log(value);
  } catch (err) {
    console.log(err); // 👉️ "Something went wrong"
  }
}

example();

我们使用 Promise.reject() 方法来获得被拒绝的承诺。 当我们尝试等待 promise 时,我们的 catch 函数被调用并传递了拒绝的原因。

在许多用例中,我们可能希望在函数外部使用 await 运算符。

// 👇️ Example promise
const p = Promise.resolve('Hello world');

try {
  const value = await p;
  console.log(value); // 👉️ "Hello world"
} catch (err) {
  console.log(err);
}

如果我们的 Node 版本高于 16.12.0,则顶级 await 语法在 Node.js 中可用。

如果打算在浏览器中使用顶级 await,请查看 caniuse 表以了解浏览器对顶级 await 的支持。

在撰写本文时,通过将 JavaScript 文件作为模块加载到 html 文件中,可以为大多数现代浏览器启用顶级 await 运算符。

index.html

<!-- ✅ Your JS script here ✅ -->
<script type="module" src="index.js"></script>

请注意 ,我们将类型属性设置为模块。

使用顶级 await 时,使用 try/catch 块非常重要,因为拒绝 promise 导致的未捕获异常可能会阻止我们的应用程序运行。

// 👇️ Example rejected promise
const p = Promise.reject('Something went wrong');

try {
  const value = await p;
  console.log(value);
} catch (err) {
  // 👇️ catch the error here
  console.log(err); // 👉️ "Something went wrong"
}

如果未处理对 promise 的拒绝,例如 在 catch 块中,您的服务器可能处于不一致状态。

在使用 await 运算符时,最好使用 try/catch 块。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便