0

I define a javascript that looks like thise:

async function searchPerson(item){
    const url = window.location;
    const response = await fetch(url.origin+"/api/persons/search/1/"+item);
    const person = await response.json();
    //console.log(person);
    return person;
}

and so in my eventListener, i am calling that method just like this:

if(document.getElementById('search-person')){
    document.getElementById('search-person').addEventListener('click', (e)=>{
         item = document.getElementById('input_search_person_ref_number').value;
         if(item){
             const person= async ()=>{
                 searchPerson(item);
             }
             //const person = await searchPerson(item);
             console.log(person);
         } 
    }
}

Upon running i am getting an out put like this:

async ()=>{
    searchPerson(item);
}

if i use const person = await searchPerson(item); i have to make addEventListener async too. Is there other way to get it (return value promise) without making addEventListener asynchronous?

FZs
  • 16,581
  • 13
  • 41
  • 50
Anirudh Lou
  • 781
  • 2
  • 10
  • 28
  • 2
    You cannot expect to get a *future* result *now*. So you must embrace the `async` pattern *all the way*. So `searchPerson(item).then(console.log)` – trincot Dec 08 '19 at 09:11
  • 2
    When calling an async function, you must either `await` it, or call `.then` on the resulting Promise. No good other way around it – CertainPerformance Dec 08 '19 at 09:11
  • Thank you very much for pointing it to me. By the way, is promise specify only for ES6 onwards? How can i detect if my javascript code is old one? – Anirudh Lou Dec 08 '19 at 10:22

0 Answers0