如何使用从一个模块提取到另一个模块导出从 GET API 获得的响应数据

How to export the response data obtained from a GET API using fetch from one module to another

代码片段:

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

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

现在我知道,由于解析承诺是异步的,因此数据将为 {}。 但是,如果我尝试从 handleget 函数内部导出,则会收到一条错误消息,指出 import export 应该位于文档的顶层。

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

你不能。

它是异步的。

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

将从 catch 返回的承诺分配给 data

导入后处理promise。

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 => ...);

使用 Quentin 提供的答案,这是我的最终代码以及来自获取请求的错误处理的样子

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

export default data

//App.js
import data from "./Logic.js";

async function fetch_this_data()
    {
        const res = await data.then(result => result);
        
            if (res.status == 200)
            {
                console.log("res"+JSON.stringify(res.body));
                return res.body;
            }
            else
            {
                console.log("resu"+JSON.stringify(res));
                return "Error!! Status "+res.status;
            }
        
    }

fetch_this_data();