问题
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;
}
}
})
}
回答1:
I'm fairly certain you can't do what you want, at least not directly.
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
and export
are decided synchronous, so you won't be able to mix and match them with an asynchronous function.
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
来源:https://stackoverflow.com/questions/43687092/how-to-export-an-object-returned-by-async-await-method