【问题标题】:How to pass a value to async function in JS如何将值传递给JS中的异步函数
【发布时间】:2020-01-04 15:30:46
【问题描述】:

我正在尝试了解如何使用异步/等待从外部 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 对象显示在控制台中。到目前为止,它所做的是将输入值记录到控制台。

【问题讨论】:

    标签: javascript async-await fetch-api


    【解决方案1】:

    你没有向方法传递任何东西:

    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));
    };
    

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 1970-01-01
      • 2020-08-03
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      相关资源
      最近更新 更多