Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export an object returned by async/await method

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;
      }
    }
  })
}
like image 437
TechTurtle Avatar asked Apr 28 '17 18:04

TechTurtle


2 Answers

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

like image 75
samanime Avatar answered Oct 10 '22 02:10

samanime


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;
like image 2
bergy Avatar answered Oct 10 '22 03:10

bergy