【问题标题】:How can i use my data from a api and pass it into another function for further processing我如何使用来自 api 的数据并将其传递给另一个函数以进行进一步处理
【发布时间】:2021-10-28 14:50:03
【问题描述】:

有什么方法不使用 setTimeout() 来允许将 fetch 中的数据存储在 stored_data 数组中,然后允许测试函数进行操作。

到目前为止我还没有定义。

let stored_data = []


fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => stored_data.push(json))


function test(e) {
console.log(e)
}

【问题讨论】:

    标签: javascript arrays function


    【解决方案1】:

    您可以简单地链接另一个.then。您还忘记将store_data 声明为变量

    let stored_data = []
    
    fetch('https://jsonplaceholder.typicode.com/todos/1')
          .then(response => response.json())
          .then(json => stored_data.push(json))
          .then( _ => {
              // array now ready for manipulation
          })
    

    【讨论】:

    • 感谢您的回复,但我希望访问函数外的stored_data。
    • 问题是你不能。要么用.then 链接它,要么将它包装在一个异步函数中并等待获取。这是你的两个选择。
    • 哦,好的,谢谢,我明白了,如果我想要另一个函数来使用 stored_data id,则必须在希望使用 stored_data 的新函数内部调用带有 .then 的异步函数。
    • 没有。您必须在 fetch 上链接 .then 的唯一原因是因为 fetch 本身是异步的。您必须保证在您访问stored_data时,fetch已经解析,因此您可以通过仅在fetch已解析时访问stored_data来做到这一点,这可以通过.then完成。
    猜你喜欢
    • 2022-01-23
    • 2023-03-19
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多