0

Im trying to learn async/await syntax and just not making any progress. I have a snippet below that so far returns me this to the console. The idea is that if my map doesnt have a particular key in it, that it will make a callout - wait for response - and then continue. Instead, I just get the promise. Any pointers on where Im going wrong would be really appreciated.

enter image description here

    // mymap is a global var
async function retrieveDetails(key){
    let url = '/myurl);
    let res = '';
    const response = await fetch(url, {
        headers: {
        'Content-Type': 'application/json',
        'Authorization' : 'Bearer '+accessToken
        }
    })
    .then((response) => {
        mymap.put(key, response);
    })
}

function getValue(key){
    if(!mymap.has(key)){
        retrieveDetails(key);
    }
    return mymap.get(key); 
}

let result = getValue('foo'); // should return me a value from mymap.
user1517566
  • 348
  • 1
  • 3
  • 14
  • 2
    `let url = '/..myurl);` This doesnt look right. Are you sure the code you pasted here is exactly as the one you are using? – Suraj Rao Feb 07 '23 at 03:44
  • The url Im using works fine. I have just removed the bulk of the redundant code. Its the promise part that I cant get my head around. None of the examples Ive looked at have a fetch..then() inside them. – user1517566 Feb 07 '23 at 04:02
  • 1
    @user1517566 it should be something like `let url = '/..myurl';`, because you never closed the string – Samathingamajig Feb 07 '23 at 04:05
  • If you're using javascript maps, you cannot use put. Set is the one you want. Are you sure you're not also getting errors from that, as well as Samathing's answer? – nugenjs Feb 07 '23 at 04:10

1 Answers1

1

Just because you use await inside of retrieveDetails doesn't mean that when you call retrieveDetails that it will wait for retrieveDetails to be done (in fact it never will, unless you await or .then it).

getValue needs to be an async function (which implicity returns a Promise), or return a Promise as a synchronous function, to be able to resolve to the value you want.

With Promises,

function getValue(key){
    if(!mymap.has(key)){
        return retrieveDetails(key).then(() => mymap.get(key));
    }
    return Promise.resolve(mymap.get(key)); 
}

With async

async function getValue(key){
    if(!mymap.has(key)){
        await retrieveDetails(key);
    }
    return mymap.get(key); 
}

Either way, you need to change how you receive the data:

let result = await getValue('foo');

// or

getValue('foo').then((result) => {
  // rest of code
});
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • Appreciate the detailed response! Your opening comments got me focused on correct use of await and I think I understand the flow better now. Very helpful thank you. – user1517566 Feb 07 '23 at 04:28