如何导出异步/等待方法返回的对象 [英] How to export an object returned by async/await method

查看:54
本文介绍了如何导出异步/等待方法返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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 export 被确定为同步,因此您将无法使用异步功能对其进行混合和匹配.

import and export are decided synchronous, so you won't be able to mix and match them with an asynchronous function.

第二个示例的问题是您设置了 client = null .当您稍后将其设置为对象时,就是将该变量设置为对象,但是在导出时导出了 client value

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

这篇关于如何导出异步/等待方法返回的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆