JavaScript-未捕获的TypeError:postData(…).则不是函数

前端之家收集整理的这篇文章主要介绍了JavaScript-未捕获的TypeError:postData(…).则不是函数 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我已经设置了一个按钮,单击该按钮将通过获取发布数据并创建警报.但是,我首先检查以确保某些输入不为空.如果输入元素没有值,我尝试返回一个字符串,告诉我哪个输入元素值是空的.当我这样做时,会出现“ Uncaught TypeError:postData(…).then 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
};
最佳答案
当检测到“错误”时,您将返回一个字符串值而不是promise. then方法仅在promise上存在.

将您的函数更改为async,以便默认情况下返回一个Promise.

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 data type must match "Content-Type" header
});

//res.json() returns a promise,so use await
return await res.json();
原文链接:https://www.f2er.com/js/531091.html

猜你在找的JavaScript相关文章