How to export an object returned by async/await method

有些话、适合烂在心里 提交于 2021-01-26 07:01:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!