检查来自promise的JSON对象是否为null

问题描述

我打开了另一个类似的话题,但得到了负面的回应。我在这里面临一个合法问题,并向您保证我已对此进行了广泛研究。我相信我真正的问题可能是语法,因为我不是精通JS编码器。这是一个令人尴尬的2周的持续斗争。我有以下内容

fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
  .then(response => response.json())
  .then(data => instance.setValue(data[0].data.endingPettyTotal));
@H_404_4@

我正在尝试查看JSON对象,如果它的长度为零,请将我的data.engingPettyTotal设置为'0'。如果不为零,则将其设置为等于JSON对象的值,就像我上面所说的那样。

似乎我应该能够通过检查response.json()。length来完成此操作,

fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
    .then(response => {
        if(response.json().length === 0) {
            console.log("empty")
            return 0;
        }
        else {
            console.log("not empty")
            return 
        })
    .then(data => instance.setValue(data[0].Balance));
    }
@H_404_4@

不幸的是,这似乎也不起作用。再次,假设我刚刚弄乱了语法或其他东西,但是再次,这个异步的东西令人困惑。还假设可以使用lodash(isEmpty或isNull)完成此操作。

解决方法

response.json()返回的承诺将与服务器发送的数据一起解决

在第二个then()中进行检查

fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
  .then(response => {
        if(!response.ok){
           return Promise.resolve(0)// or just throw error
        }
       return  response.json())
  }).then(data => 
        // if not array or empty array set as zero
        const val = (Array.isArray(data) && data.length) ? data[0].Balance : 0;
        instance.setValue(val);
   })
,

response.json()返回一个Promise对象,请尝试:

fetch('http://your.url')
  .then(response => response.json())
  .then(data => instance.setValue(data.length && data[0].Balance));

或者如果data.length等于0不想设置值:

fetch('http://your.url')
  .then(response => response.json())
  .then(data => data.length && instance.setValue(data[0].Balance));
,

您没有返回从第一个回调函数返回JSON的promise。

将支票放入第二个[...]

.then()
,

很难确切说明参数的名称是什么……它们在服务器端是“ data.dateofService”吗? (假设它只是“ dateOfService”)

通过json / FormData发送数据在PHP方面有不同的处理方式。 发送json的替代方法-是new FormData()...和append('key',“ value”); 而不是jsonData,将formData附加到body属性。

const sendData = {
  dateOfService: data.dateChanger,select:data.endingPettyTotal
}
const jsonData = JSON.stringify(sendData);
const options = {
  method:"POST",body: jsonData
}
fetch('https://example.com/api/submission',options)
  .then(response => response.json())
  .then(data=>
    {
    if(data.length == 0) {
      console.error("no data")
    }
    else {
      console.log("not empty")
      instance.setValue(data[0].Balance);
  }
});