【问题标题】:How can I fetch a javascript file and store the response object as an array?如何获取 javascript 文件并将响应对象存储为数组?
【发布时间】:2022-01-08 04:23:32
【问题描述】:

我正在尝试获取 javascript 文件并将响应对象作为数组返回。我的 javascript 文件只是一个数组,例如 ["1", "2", "3", ...] 这是我现在的代码:

function getNames() {
 let data = fetch('/path/to/file')
 .then((response) => response.json())
 .then(data => {
   console.log(data);
 return data()
 })
 .catch(error => {
   return error;
 });
}

我需要找到一种在函数之外使用数据变量的方法。我该怎么做?

【问题讨论】:

标签: javascript api fetch-api


【解决方案1】:

let data = [];
(
  function() {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(response => response.json())
      .then(json => {
        data = [...json]
      })
  }

)();

// this is outside - might be empty, if the response does
// not arrive under 3 seconds
setTimeout(() => {
  console.log("data in setTimeout", data)
}, 3000)

如果您想响应式更新应用程序的状态(基于该区域是否已到达),那么您应该使用响应式库/框架,例如 React、Vue、Angular 或 Svelte。 (当然,您可以创建自己的反应系统,但以后可能会受到限制。)

【讨论】:

    【解决方案2】:

    您使用的是node.js,所以如果您使用module.exports,则可以使用require()

    ./someFile.js

    module.exports = {
      foo: "bar"
    }
    

    ./otherFile.js

    const data = require("./someFile.js")
    console.log(data.foo) // "bar"
    

    如果您要求从文件中获取简单的数组或对象,您应该使用.json 文件,并使用require(),就像在第一个示例中一样。如果要获取当前数据,而不是第一次需要时获取的数据,请使用fs 模块

    ./array.json

    [
      "1",
      "2",
      "3"
    ]
    

    ./otherFile.js

    const fs = require("fs")
    const data = JSON.parse(
      fs.readFileSync("./array.json", "utf8")
    )
    console.log(data) // [ "1", "2", "3" ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-05
      • 2019-12-22
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2014-06-09
      相关资源
      最近更新 更多