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.
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
This is now possible in modern browsers with Top level await. Be sure to check browser support at the table below the example.
A simple example using fetch from MDN:
const colors = fetch('../data/colors.json')
.then(response => response.json());
export default await colors;
The original script can be written like below and work as OP intended:
const client = HttpService.getValueFromSettings('durl').then((response) => {
if(isValidResponse(response)) {
return createClient(response.data);
}
return null;
};
export default await client;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With