使用javascript

时间:2018-08-20 14:18:48

标签: javascript async-await

我创建了一个返回JSON的api。我正在使用javascript,我想做的是从json中保存.ContactID并将该值分配给全局变量contactID。我是新手,我可以确定我的问题是我的代码没有等待数据从服务器返回。.

<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>

2 个答案:

答案 0 :(得分:0)

未测试:

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

此函数应在异步上下文中调用并等待其结果

答案 1 :(得分:0)

您可以

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

然后调用

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

应该可以。