可以自调用异步函数 returns public 函数

Can Self Invoking Async function returns public functions

我实际上是 JavaScript 的新手。所以这是我的问题。

从我学到的。我可以在自调用函数 (Example1) 中创建一个 public 函数 (getHello) 并调用创建的 public来自另一个自调用函数 (Example2) 的函数,如下所示:-

// first self-invoke function
const Example1 = (() => {
    // daclare var to hold Hello World
    let hello = 'Hello World'

    return {
        // create public function to passed 'Hello World'
        getHello: () => {    
            return hello
        }
    }
})();

// second self-invoke function - receive 1 argument (Example1 function)
const Example2 = ((e1) => {
    // declare new var
    let newHello = e1.getHello()
    console.log(newHello) // will Output: Hello World

})(Example1);

我试过上面的代码,效果很好。从来不知道 JavaScript 可以这么有趣!这意味着只要我创建一个 Example1 内的 any private 'data' 基本上可以共享给任何其他自调用函数=62=] 启用数据共享功能。

无论如何,记住这一点。我想为什么不创建一个 专用的自调用函数 来处理从 API 获取的任何 数据。所以要做到这一点,我需要将 async 放在自调用函数中,以便使用 await 获取 json 数据 (如下所示)

// first async self-invoke function
const Example1 = (async() => {
    // get data from API fetch
    let res = await fetch(API_URL)
    let json = await res.json()
    let hello = json

    return {
        // create public function to passed 'Hello World'
        getHello: () => {    
            return hello
        }
    }
})();

// second self-invoke function - receive 1 argument (Example1 function)
const Example2 = ((e1) => {
    // declare new var
    let newHello = e1.getHello() // error occurs here
    console.log(newHello)

})(Example1);

但不幸的是,这样做。它给了我这个错误说 "e1.getHello is not a function".

我已经尝试在 google 上搜索答案或任何解释。但我似乎找不到任何相关主题来讨论我刚刚在这里说明的内容。

所以问题是;-

1) 异步自调用函数 returns 完全可以是 public 函数吗?或者我根本不应该或不建议这样做?

2) 如果can/cannot,那为什么?

如有任何帮助,我们将不胜感激!

async 函数 returns Promise 对象。在给定的示例中,Example1 将是一个 Promise 对象,而不是纯对象。

所以如果你想使用它,你必须使用thenawait来获取promise中的值。

这将按预期工作:

const Example1 = (async() => {
    let res = await fetch(API_URL)
    let json = await res.json()
    let hello = json

    return {
        getHello: () => {    
            return hello
        }
    }
})();

const Example2 = (async (e1) => {
    el = await e1; // **** THIS IS KEY POINT ****
    let newHello = e1.getHello()
    console.log(newHello)
})(Example1);