繁体   English   中英

如何在JS中将值传递给异步函数

[英]How to pass a value to async function in JS

我试图了解如何使用async / await从外部API获取数据。 我正在尝试从openFDA API获取数据。 当用户输入药物时,API会检索数据并将其显示在网页上。 输入值未传递给异步函数。

我看过其他教程,但让我更加困惑。

//listens for the submit event and calls the getMeds function
const myForm = document.querySelector('#form').addEventListener('submit',getMeds);
// get the input value from the user
function getMeds(e){
    const meds = document.querySelector('#searchbox').value;

    console.log(meds);

     e.preventDefault(); 

};
//get medication information from the OpenFDA API

const getMedicine = async (meds) => {

    const base = 'https://api.fda.gov/drug/label.json';
    const query = `?search=openfda.brand_name:${meds}%limit=5`;

    const response = await fetch (base + query);
    const data = await response.json();

    return data

    };

     getMedicine()
        .then(data => console.log(data))
        .catch(err => console.log(err)); 

我希望.json对象显示在控制台中。 到目前为止,它所做的是将输入值记录到控制台。

您没有将任何内容传递给该方法:

getMedicine()

注意整个代码中将值传递给方法的各种方式:

  • querySelector('#form')
  • addEventListener('submit',getMeds)
  • querySelector('#searchbox')
  • log(meds)
  • 等等

这正是将值传递给方法的方式。 直接包含它,或在调用方法时将其作为变量包含。 无论您想传递给方法的值是什么,都可以传递给它:

getMedicine(someValueHere)

例如,如果您在提交处理程序中调用它:

function getMeds(e){
    e.preventDefault(); 
    const meds = document.querySelector('#searchbox').value;
    getMedicine(meds) // <--- pass the value to the function
        .then(data => console.log(data))
        .catch(err => console.log(err));
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM