Javascript fetch/get 请求/2 次/3 次点击按钮

问题描述 投票:0回答:1

嗨,我对 JS 比较陌生,

我有一个“奇怪”的问题,我有两个输入字段,当我单击 sndbtn (clickEventListener)时,然后调用 3 个函数,所有函数都带有 fetch/get 请求,然后返回一个 json 对象。

但是当我单击按钮时,首先我得到一个未定义的对象,当我第二次单击时,我得到第一个对象....第三个第二个对象等等...所以我必须单击3次并且它可以工作.

也许有人可以解释我如何让它在第一次点击时工作:-)

谢谢

let vonPlz;
let nachPlz;
let vonOrt;
let nachOrt; 
let km;
let kilometer;
let sendBtn;
let vonLon;
let vonLat;
let nachLon;
let nachLat;
let vonJson;
let nachJson;


document.addEventListener('DOMContentLoaded', function(event)  {
    vonPlz = document.getElementById("vonPlz");
        nachPlz = document.getElementById("nachPlz");
        vonOrt = document.getElementById("vonOrt");
        nachOrt = document.getElementById("nachOrt");
        km = document.getElementById("km");
        sendBtn = document.getElementById("sendBtn");
    
    
    sendBtn.addEventListener('click', function() {
        
        getReqVonPlz(vonPlz.value);
        getReqNachPlz(nachPlz.value);
        
        console.log(vonJson[0].display_name);
        console.log(nachJson[0].display_name);
        
        vonLat = vonJson[0].lat;
        vonLon = vonJson[0].lon;
        nachLat = nachJson[0].lat;
        nachLon = nachJson[0].lon;
        
        postReqKm(vonLat, vonLon, nachLat, nachLon);
        console.log(kilometer);
        vonOrt.innerHTML = vonJson[0].display_name;
        nachOrt.innerHTML = nachJson[0].display_name;
        km.innerHTML = kilometer;
    })

   
});

 
    
async function getReqVonPlz(plz){
    await fetch("https://nominatim.openstreetmap.org/search?format=json&country=de&postalcode=" +plz , {
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
        })
        .then((response) =>  response.json())
        .then((json) => {vonJson = json});
         
        
}

async function getReqNachPlz(plz){
    await fetch("https://nominatim.openstreetmap.org/search?format=json&country=de&postalcode=" +plz , {
        method: "GET",
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
        })
        .then((response) => response.json())
        .then((json) => {nachJson = json});

        
}


async function postReqKm(vonLat, vonLon, nachLat, nachLon){
    await fetch("https://api.openrouteservice.org/v2/directions/driving-car", {
    method: "POST",
    body: JSON.stringify({
        coordinates: [[vonLon,vonLat],[nachLon,nachLat]],
       
    }),
    headers: {
        "Content-type": "application/json; charset=UTF-8",
        "Authorization": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    }
    })
    .then((response) => response.json())
    .then((json) =>  {kilometer = json.routes[0].summary.distance});
}

首先我没有添加 async-await 函数?,当我只使用一个有效的函数测试它时,现在我对所有 3 个函数执行 async 和 wait,但我必须单击 3 次:-(

所以我认为问题出在某个地方,但我对此真的很陌生。

javascript async-await fetch-api jsonobjectrequest undefined-variable
1个回答
0
投票

javascript 是异步的,这意味着它不会等待函数执行完成。因此,您需要强制使您的功能同步。

代码的当前行为

执行 getReqVonPlz 无需等待 执行 getReqNachPlz 无需等待 执行 postReqKm 无需等待

期望的行为 执行 getReqVonPlz 并等待 执行 getReqNachPlz 并等待 根据上述函数结果执行postReqKm

有多种方法可以实现此目的,首选方法是:

  1. 承诺链
  2. 使用等待或等待全部

我将在这个答案中演示await的示例

var [vonJson, nachJson] = await Promise.all([getReqVonPlz(vonPlz.value), getReqNachPlz(nachPlz.value)]);
vonJson = vonJson.json();

nachJson = nachJson.json();

var res = await postReqKm(vonLat, vonLon, nachLat, nachLon);
//process your res

让你的函数返回承诺,例如。

function getReqNachPlz(plz){
return fetch("https://nominatim.openstreetmap.org/search?format=json&country=de&postalcode=" +plz , {
    method: "GET",
    headers: {
        "Content-type": "application/json; charset=UTF-8"
    }
    });

}

© www.soinside.com 2019 - 2023. All rights reserved.