javascript - 未捕获的 TypeError: postData(...).then 不是函数
问题描述
我已经设置了一个按钮,单击该按钮将通过 fetch 发布数据并创建警报。但是,我首先检查以确保某些输入不为空。如果输入元素没有值,我会尝试返回一个字符串,告诉我哪个输入元素值为空。当我这样做时,会出现“Uncaught TypeError: postData(...).then is not a function”错误。我还查看了Uncaught TypeError: $.get(...).then is not a function但无法弄清楚。任何帮助将不胜感激。谢谢!
document.getElementById("sbmForm").onclick = function () {postData(`/projectInfo`)
.then(result => alert(JSON.stringify(result))) // JSON-string from `response.json()` call
.catch(error => alert(error))};
function postData(url = ``) {
// get form data from local storage
var data = {};
var unqVal = document.getElementById("unq_num").innerHTML;
unqVal = "--??**" + unqVal;
// keys that can not be empty
var notEmpty = ["comp_name", "compaddr_str_num", "compaddr_str_nam", "compaddr_city",
"compaddr_state", "compaddr_zipcode", "proj_name", "projaddr_str_num", "projaddr_str_nam",
"projaddr_city", "projaddr_state", "projaddr_zipcode", "contact_fname", "contact_date"];
/* get all keys and values from local storage and store them in dict to send to server */
var keys = Object.keys(localStorage);
var i;
for (i=0; i < keys.length; i++){
var val = localStorage.getItem(keys[i]);
// if unq val is in string, add it to the data
var indexOf = keys[i].indexOf(unqVal);
if (indexOf != -1){
var keyNU = keys[i].substring(0, indexOf);
// if value is in array
if (notEmpty.includes(keyNU)){
// if value is empty
if (!val){
alert(keyNU + " cannot be empty!");
/**** ERROR OCCURS HERE *****/
return keyNU + " cannot be empty!";
}
}
data[keys[i]] = val;
}
}
// Default options are marked with *
return fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
};
解决方案
当检测到“错误”时,您返回的是字符串值而不是承诺。该then
方法仅存在于 Promise 上。
将您的更改function
为async
,使其promise
默认返回 a 。
async function postData(url = ``){}
然后在需要发生时抛出错误(将被catch
方法捕获)通过更改此
/**** ERROR OCCURS HERE *****/
return keyNU + " cannot be empty!";
至
throw new Error(keyNU + " cannot be empty!");
最后,为了您的获取:
//fetch returns a promise, so use await
const res = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
//res.json() returns a promise, so use await
return await res.json();
推荐阅读
- google-sheets - 为什么我在谷歌表格中得到一个文字数组错误?
- youtube-api - 视频统计 - youtube api
- c# - 填充同一个数据集的不同数据表是线程安全的操作吗?
- javascript - getSecretValue 回调在 AWS Lambda 中不起作用
- javascript - 从数据库中解析 HTML 代码并将其显示在 div 中
- javascript - Node.js:Express 为 CloudFront 设置“信任代理”
- python - 减少芹菜队列中的积压
- flutter - 从 TabBarView 的子级导航到另一个页面会引发错误
- python - 在 Linux 上安装 AssimpCy
- c# - 为什么asp.net零应用服务没有try and catch异常?