如何导出异步/等待方法返回的对象

Tec*_*tle 6 javascript asynchronous async-await

由于异步总是返回promise,因此我们必须解决它才能获得价值。我需要导出它的值(返回的对象),以便我们可以在另一个模块中使用它。

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
      }
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

我需要在另一个模块中使用客户端。

我尝试在调用之前声明和初始化客户端对象,但没有成功:

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;
      }
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

sam*_*ime 6

我相当确定您不能做您想做的事情,至少不能直接做。

相反,您应该只导出getClient()函数本身,并在需要客户端时调用它。

import { getClient } from './myfile';

getClient().then(client => { someOtherFunction(client); });
Run Code Online (Sandbox Code Playgroud)

import并且export被确定为同步,因此您将无法将它们与异步功能混合搭配。

第二个示例的问题是您设置了client = null。当你再后来将其设置为一个对象,你设置该变量的对象,但您导出的价值client,在出口