-1

I created an api that returns JSON. I am using javascript and what I am trying to do is save the .ContactID from the json and assign that value to the global variable contactID. I am new at this and I am sure my problem is that my code is not waiting for the data to come back from the server..

<script>


const contactID =getContactIDfromServer();


async function getContactIDfromServer(){
// Replace ./data.json with your JSON feed
fetch('https://cnx2zr39y8.execute-api.us-west-2.amazonaws.com/Production?Name=hector%20Salamanca').then(async response => {
  return await response.json();
}).then (async data => {
  // Work with JSON data here
  var parsed = await JSON.parse(data);
  //document.getElementById("demo").innerHTML = "This is inside function "+parsed.ContactID;    
  var stuff =await parsed.ContactID;
  console.log('This is inside '+stuff);
  return stuff;
}).catch(err => {
  // Do something for an error here
});
}

console.log('this is outside '+contactID);
</script>
AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • 2
    Do not mix async/await and Promises – Naramsim Aug 20 '18 at 14:20
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – zero298 Aug 20 '18 at 14:20
  • `async`/`await` makes *asynchronous* things easy, but it doesn't make the synchronous. `contactID` is still a promise. – Bergi Aug 20 '18 at 14:23
  • Don't use `then` when you can `const data = await fetch(…);` – Bergi Aug 20 '18 at 14:23

2 Answers2

0

Not tested:

async function getContactIDfromServer() {
    try{
        const response = await fetch('https://cnx2zr39y8.execute-api.us-west-2.amazonaws.com/Production?Name=hector%20Salamanca')
        const parsed = await response.json()
        const stuff = parsed.ContactID
        console.log('This is inside ' + stuff)
        return stuff
    } catch(error) {
        throw error
    }
}

This function should be called in an async context and awaited for its result

Naramsim
  • 8,059
  • 6
  • 35
  • 43
0

You can do

async function getContactIDfromServer(){
    // Replace ./data.json with your JSON feed
    try{
        const response = await fetch('https://cnx2zr39y8.execute-api.us-west-2.amazonaws.com/Production?Name=hector%20Salamanca')
        const data = await response.json();
        let parsed = JSON.parse(data);
        let stuff = parsed.ContactID;
        console.log('This is inside ', stuff);
        return stuff;
    } catch(e) {
        // Do something for an error here
    }
}

And then call as

getContactIDfromServer().then(res => console.log(res))

That should work.

pritesh
  • 2,162
  • 18
  • 24