【问题标题】:Assigning the value of a fetch request to a Javascript Object Property returns undefined [duplicate]将获取请求的值分配给 Javascript 对象属性返回未定义 [重复]
【发布时间】:2017-07-15 15:12:06
【问题描述】:

通过 Fetch API 获取数据,我需要将响应分配给一个变量,该变量将在许多情况下使用,例如全局值。

最合适的方法是创建一个对象并将获取响应分配给它的一个属性。

  var number = 0;

  fetch(url, numberValue);  // fetch data from API,  returns a string like "5489721"

  function numberValue(response)  {// invoked by fetch, it's parameter is the fetch response.
    this.number = response:
    // console,log('number='+this.number): // 43090
   }

   console.log("number value outside function value="+ new numberValue().number):  // prints undefined.

但是我发现在创建对象的函数内部,分配的值运行良好,但是如果我在它的构造函数外部调用对象,我会得到一个“未定义”的值。

但是,如果我分配一个固定值,我会得到正确的值,这让我认为问题出在 json 响应上,但它在它的构造函数中完美运行。

获取函数是这样的:

function fetchGet(url, functionName) {
  fetch(url, {
    method: 'GET'
 }).then(function(response) {
    return response.json();
 }).then(function(json) {
    functionName(json);  // here I invoke other function to process response.
 }).catch(function(err) {
}

在页面加载时调用,如下所示:

 var url =""; // API endpoint, gives a plain "525554"
 fetchGet(url, value);

 function value (response) {
   console.log('response='+response);  //52554
 }

但是,除了捕获普通值之外,我还需要在命名空间中公开此值,以便其他功能使用。

【问题讨论】:

  • 您能否记录 JSON 响应以查看您是否收到了一个号码?
  • 在您的示例中,您没有为“response”变量分配任何值,然后将其分配给this.number,因此该值未定义。如果这不是问题,请提供您的完整代码
  • 响应是一个json字符串,和这个“32250”一模一样,是一个API的输出。
  • 请包含 fetch api 代码,以便更容易获取您使用此回调的上下文/视角。
  • 您的(第一个)console.log 没有记录正确的值,因为fetch 是异步的,并且您试图在获取值之前记录它。

标签: javascript oop object fetch-api


【解决方案1】:

内容:data/example-fetch-1.json

{
  "foo": "Hello",
  "bar": "World"
}

内容:data/example-fetch-1.json

{
  "foo": "Be",
  "bar": "Yah"
}

类定义、用法:

'use strict';
class jsonData {
    constructor(url) {
        let thisObject = this;
        thisObject.dataJson = null;
        thisObject.dataUrl = url;
        thisObject.fetchData = function (url) {
            if (!!url) {
                thisObject.dataUrl = url;
            }
            fetch(thisObject.dataUrl, {
                method: 'GET'
            }).then(function (fetchResponse) {
                return fetchResponse.json();
            }).then(function (fetchResponseJson) {
                thisObject.postProcess(fetchResponseJson);
            }).catch(function (doh) {
                throw new Error(doh);
            });
        }
        thisObject.message = function () {
            let bar = 'DOH';
            let foo = 'doh';
            let jsonDataExists = !!thisObject.dataJson;
            if (jsonDataExists) {
                let incomingData = thisObject.dataJson;
                bar = incomingData.bar || bar;
                foo = incomingData.foo || foo;
            }
            return foo+' '+bar+'!';
        }
        thisObject.postProcess = function (responseJson) {
            thisObject.dataJson = responseJson;
            console.log('jsonData.message() = ', thisObject.message());
        }
    }
}
var jsonDataGetter = new jsonData('data/example-fetch-1.json');
jsonDataGetter.fetchData();
jsonDataGetter.fetchData('data/example-fetch-2.json');

【讨论】:

  • 使用此代码,总是给我 '43090' 值,而不是响应值。
  • 那么,您只是希望有一个回调函数返回任何值响应?
  • 是的,我需要将响应的值公开为其他函数可以访问的变量。我从 API 获取一个 json 编码的字符串,给我像“41087”这样的响应,需要公开这个值,每次获取它都会改变。函数 value() 由 fetch 方法调用,并作为参数接收 fetch 响应。
猜你喜欢
  • 2019-06-17
  • 2016-03-19
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
  • 2017-11-30
  • 2016-10-14
  • 2019-10-10
相关资源
最近更新 更多