类中静态代码块和静态属性值_承诺和静态值

类中静态代码块和静态属性值

Async can throw a real wrench into the cogs of our programming workflows, all despite the fact that async is the modern JavaScript pattern. While async/await helps, there's sometimes confusion about the way to have a single function that returns a value whether it exists or needs a Promise to retrieve.

尽管事实上异步是现代JavaScript模式,但Async确实可以使我们的编程工作流程陷入困境。 尽管异步/等待会有所帮助,但有时对于使单个函数返回值(无论该值是否存在还是需要Promise)的方式有些困惑。

The key thing to remember is that functions declared as async automatically return a Promise, so you don't need explicity return the existing content with Promise.resolve(content):

要记住的关键是,声明为async函数会自动返回Promise,因此您无需通过Promise.resolve(content)显式地返回现有内容:

async function getValueOrFetch(ojbOrInfo) {
  // If the value exists, immediately return it
  if(ojbOrInfo) {
    return ojbOrInfo;
  }
  // Return the promise-based info
  return asyncFunctionToGetInfo(ojbOrInfo);
}

Let's look at a real life example: returning cached contents instead of doing a fetch call to retrieve them:

让我们看一个真实的例子:返回缓存的内容,而不是执行fetch调用来检索它们:

const cache = {
  /* url: content */
};

// Async function that returns cached content or retrieves fresh content
async function getInfo(url) {
  // Check for value in cache
  if (cache[url]) {
    // Return the content, no need for Promise.resolve
    return cache[url];
  }
  // Get the content fresh
  const content = await fetch("https://www.facebook.com").then(r => r.text());
  cache[url] = content;
  return content;
}

My main goal with this post is making you understand that return Promise.resolve(data) isn't needed with async functions -- you can simply return the value and it will be wrapped in a promise!

我写这篇文章的主要目的是让您了解异步函数不需要return Promise.resolve(data) -您只需返回该值,它将包装在一个Promise中!

翻译自: https://davidwalsh.name/promises-and-static-values

类中静态代码块和静态属性值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值