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

编程入门 行业动态 更新时间:2024-10-20 01:22:26
本文介绍了如何导出异步/等待方法返回的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

由于异步总是返回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

更多推荐

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

本文发布于:2023-11-08 20:28:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570376.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!