Fetch:使用fetch响应设置变量并从函数返回 [英] Fetch: set variable with fetch response and return from function
问题描述
我对JavaScript很新并做出反应。
我有一个组件的回调,该组件从给定id的服务器获取customer_name。
fetch工作正常,console.log正确打印全名,但最后.then中的customer_name未设置,函数返回空字符串。为什么?
I'm quite new with JavaScript and react. I have a callback from a component that gets a customer_name from a server given a id. The fetch works and the console.log prints the fullname correctly, but the customer_name in the last .then is not set, and the functions returns an empty string. Why is that?
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
let customer_name = '';
fetch(`/customers/${id}.json`, {
headers: API_HEADERS,
credentials: 'same-origin'
})
.then((response) => {
if(response.ok) {
return response.json();
} else {
throw new Error('Server response wasn\'t OK');
}
})
.then((json) => {
customer_name = json.first_name.concat(' ').concat(json.last_name);
console.log(customer_name);
});
return customer_name;
}
推荐答案
我想你不要正确理解承诺。在解析Promise之前将调用return语句,从而返回空字符串。
I think you don't understand Promises correctly. The return statement will be called before the Promise is resolved, thus returning empty string.
解决此问题的一种方法是返回如下所示的整个承诺:
One way to tackle this, is to return the whole promise like this:
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
let customer_name = '';
return fetch(`/customers/${id}.json`, {
headers: API_HEADERS,
credentials: 'same-origin'
})
.then((response) => {
if(response.ok) {
return response.json();
} else {
throw new Error('Server response wasn\'t OK');
}
})
.then((json) => {
return json.first_name.concat(' ').concat(json.last_name);
});
}
或者您可以使用ES7方法,使用async / await像这样
or you can use the ES7 approach, using async/await like this
async function tj_customer_name(id) {
const response = await fetch('some-url', {});
const json = await response.json();
return json.first_name.concat(' ').concat(json.last_name);
}
如您所见,第二种方法更清晰,更易读。
As you can see, the second approach is much cleaner and readable.
调用函数的代码中的结果相同
The result will be the same in the code which calls your function
tj_customer_name(1).then(fullName => {
console.log(fullName);
});
或
async function something() {
const fullName = await tj_customer_name(1);
console.log(fullName);
}
这篇关于Fetch:使用fetch响应设置变量并从函数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!