【问题标题】:undefined value from function in javascript [duplicate]javascript中函数的未定义值[重复]
【发布时间】:2022-01-10 18:53:09
【问题描述】:

我正在尝试从服务器获取采购订单详细信息

这是我的代码:

    function getPurchaseOrderInfo() {
      try {
        let po_ref = document.getElementById("po_ref").value;
        let data = new FormData();
        data.append("po_ref", po_ref);
        data.append("request_token", request_token);
        fetch(URL_ROOT + "purchase-orders/get_purchase_order_info", {
            method: "POST",
            body: data,
          })
          .then((res) => res.json())
          .then((msg) => {
            console.log(msg);
            return msg.status ? msg.data : false;
          });
      } catch (error) {
        console.log(error);
      }
    }

    console.log(getPurchaseOrderInfo());

This is what I got by executing the script

我不知道为什么我得到一个未定义的值而不是 console.log(msg) 中显示的对象;

我需要该对象来打印表格并向用户显示详细信息

【问题讨论】:

  • 你没有返回任何东西。 (返回获取)
  • undefined 来自console.log(getPurchaseOrderInfo());,因为该函数不返回任何内容。 console.log(msg); 清楚地记录了下面的对象。 return msg.status ? msg.data : false; 不会返回任何地方;你丢弃了那个承诺链。您是否期望这个return 语句以某种方式跨越(msg) => {...} 的函数边界?请参阅How to return the response from an asynchronous call
  • 你能解释一下为什么吗?
  • 因为没有显式返回的函数总是返回未定义的。
  • return fetch(URL_ROOT ... 请记住,它会返回一个 Promise,您需要 getPurchaseOrderInfo().then(res => console.log(res)); 一次在异步区域中始终在异步区域中。 (没有衣柜……)

标签: javascript function object return console.log


【解决方案1】:

Fetch 返回一个承诺,因此.then() 也是一个承诺。 如果您想在函数外部使用数据,您可以返回承诺并在调用函数的任何地方使用它。
这是 ES6 的一个简单示例:


function myFunc(){
    return fetch(…).then(res => res.json())
}

function anotherFunc(){
     myFunc()
        .then(data => {
             console.log(data);
         });
}

附带说明,我个人更喜欢 ES7 async/await,它对我来说更简单。

【讨论】:

    【解决方案2】:

    您也必须返回获取。您放入 then 块中的返回返回到 fetch 而不是 getPurchaseOrderInfo。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2013-06-26
      • 2014-03-05
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多