如何使用从一个模块到另一个模块的 fetch 将从 GET API 获得的响应数据导出 [英] How to export the response data obtained from a GET API using fetch from one module to another

查看:51
本文介绍了如何使用从一个模块到另一个模块的 fetch 将从 GET API 获得的响应数据导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码片段:

let data ={};

zlFetch('http://localhost:3000/new.json')
        .then(response =>  handleget(response))
        .catch(error => console.log(error));

function handleget(response)
{
   data = response.body;
}

export default data

现在我想导出这些数据,以便我可以在其他代码中导入相同的数据.

Now i would like to export this data so that i can import the same in other code.

现在我知道,由于解决 Promise 是异步的,因此数据将为 {}.但是,如果我尝试从 handleget 函数内部导出,则会收到错误消息,指出导入导出应位于文档的顶层.

Now I know that since resolving the promise is asynchronous the data will be {}. But if i try to export from inside the handleget function then i get an error saying import export should be in top level of the document.

那么如何从获取响应中提取数据并将其存储在 then() 范围之外的变量中,然后将其导出到其他位置

So how can i extract the data from a fetch response and store it in a variable outside the then() scope and then export it else where

推荐答案

你不能.

它是异步的.

data 值的导出发生在之前收到响应.

The export of the value of data happens before the response has been received.

catch 返回的承诺分配给 data.

Assign the promise returned from catch to data instead.

然后在导入后处理promise.

Then deal with the promise after you import it.

const data = zlFetch('http://localhost:3000/new.json')
        .then(response =>  resonse.body)
        .catch(error => console.log(error));

export default data;

稍后

import newthing from './myModule';
newthing.then(data => ...);

这篇关于如何使用从一个模块到另一个模块的 fetch 将从 GET API 获得的响应数据导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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