我想检索function(response)
之外的变量值。我能怎么做?请帮忙!
<script>
Test();
function Test(){
var c = "";
filter();
function filter(data) {
c = data;
console.log(data);
}
var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
fetch(url, {
method: 'GET',
})
.then(function(response){
return response.json();
})
.catch(function(error){
console.error('Error:', error);
})
.then(function(response){
//console.log('Success:', response[0].name);
filter(response[0].name);
});
}
</script>
我的结果是使用"dara@"
查找,但undefined
是这样的:
undefined
"dara@"
答案 0 :(得分:0)
您应该等待承诺成功回调(&#39;然后&#39;函数)来打印结果。
Test();
function Test() {
query().then(function(ret) {
console.log(ret)
})
function query() {
var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
return fetch(url, {
method: 'GET',
})
.then(function(response) {
return response.json();
})
.catch(function(error) {
console.error('Error:', error);
})
.then(function(response) {
//console.log('Success:', response[0].name);
return response[0].name;
});
}
}
答案 1 :(得分:0)
一个选项是await
:
Test();
async function Test(){
var c = "";
filter();
function filter(data) {
c = data;
console.log(data);
}
var url = 'https://www.json-generator.com/api/json/get/coyqwdNpWq?indent=2';
const responseJSON = fetch(url)
.then(response => response.json())
.then((responseJSON) => {
//console.log('Success:', response[0].name);
filter(responseJSON[0].name);
return responseJSON;
})
.catch(error => console.error('Error:', error))
console.log(`got ${responseJSON}`);
}
&#13;