javascript - 在函数/promise 范围之外使用对象

标签 javascript

如何在利用 .fetch 和 Promise 的函数之外使用对象?

如果我有:

getBuildList();

function getBuildList(){
  fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      initialLoad(data);

    })
    .catch(function(err){
      console.log(err);
    });
}

我想在此函数范围之外使用data

我尝试在该函数内的几乎所有位置添加返回数据,但似乎无法使其在此函数范围之外可用。 理想情况下,我只想从 API 获取此数据一次,然后在 DOM 上按下按钮时通过不同的功能重新使用获取的数据。

我已经尝试过(以及其他许多尝试):

getBuildList();
let jsonData = getBuildList();
console.log(jsonData); //expecting data from fetch. but returns undefined

function getBuildList(){
  fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      initialLoad(data);
      let myData = data;
      return myData;

    })
    .catch(function(err){
      console.log(err);
    });
}

最佳答案

只需返回 promise :

function getBuildList(){
  // (note the "return" below, otherwise result will be undefined.
  return fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
    .then(function(res){
      return res.json();
    })
    .then(function(data) {
      initialLoad(data);
      let myData = data;
      return myData;

    })
    .catch(function(err){
      console.log(err);
    });
}

然后使用 .then 使用结果:

getBuildList().then(function(jsonData){
    // use jsonData here.
}).catch(function(error){
    // Handle the error here.
});

编辑:要将结果存储在全局变量中,请编辑最后一段代码,如下所示:

var jsonData = null; // <-- global variable
getBuildList().then(function(res){
    jsonData = res;
}).catch(function(error){
    // Handle the error here.
});

点击消耗数据的示例(确保调用上述函数后)

function consumeData() {
   if (jsonData) { // <-- this will assert jsonData is truthy, meaning it's not null or undefined, in that case.
       // consume jsonData here. Remember that changing jsonData will change it GLOBALLY!.
   }
   else {
       // OOOPS, jsonData may either be not yet defined or may just be null or empty due to a misleading or wrong fetch response.
   }
}

关于javascript - 在函数/promise 范围之外使用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590337/

相关文章:

javascript - 使用 DOM 对象创建备份数组

javascript - 与 jquery ui 可排序和选项卡作斗争(想在选项卡周围移动项目)

谷歌浏览器中的javascript XSL

javascript - 用十进制计算parsint

javascript - 在移动网络应用程序上触发滑动和触摸事件? - iPhone/安卓

Javascript:查找文本文档中所有出现的单词

javascript - 如何将javascript代码结果返回到 polymer 自定义元素的<template>?

javascript - Javascript 中匿名对象的缓存

javascript - setInterval 的时间似乎不准确

javascript - ReactJS:导出工厂,捷径?