由于异步总是返回promise,我们必须解决它才能获得价值.我需要导出它的值(返回的对象),以便我们可以在另一个模块中使用它.
As Async always returns promise, we have to resolve it to get the value. I need to export it's value (returned object) so that we can use it in another module.
export const getClient = async () => { return await HttpService.getValueFromSettings('durl').then((response) => { if(isValidResponse(response)) { endpoint = response.data; export const client = createClient(response.data); //This is where getting error that we can not export in side the function } } }) }我需要在另一个模块中使用客户端.
I need to use client in another module.
我试图在调用之前声明和初始化客户端对象,但是没有用:
I tried to declare and initialize client object before calling, but didn't work:
export let client = null; export const getClient = async () => { return await HttpService.getValueFromSettings('durl').then((response) => { if(isValidResponse(response)) { endpoint = response.data; client = createClient(response.data); return client; } } }) } 推荐答案我敢肯定,您不能做自己想做的事情,至少不能直接做.
I'm fairly certain you can't do what you want, at least not directly.
相反,您应该只导出 getClient()函数本身,并在需要客户端时调用它.
Instead, you should just export the getClient() function itself and just call that when you need the client.
import { getClient } from './myfile'; getClient().then(client => { someOtherFunction(client); });import 和 export 被确定为同步,因此您将无法使用异步功能对其进行混合和匹配.
import and export are decided synchronous, so you won't be able to mix and match them with an asynchronous function.
第二个示例的问题是您设置了 client = null .当您稍后将其设置为对象时,就是将该变量设置为对象,但是在导出时导出了 client 的 value 值
The problem with your second example is you set client = null. When you then later set it to an object, you are setting that variable to an object, but you exported the value of client at export
更多推荐
如何导出异步/等待方法返回的对象
发布评论