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

    技术2022-07-11  132

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

    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

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

    Processed: 0.010, SQL: 9