Javascript 获取:使用获取响应设置变量并从函数返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38869197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch: set variable with fetch response and return from function
提问by k3rn31
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?
我对 JavaScript 和反应很陌生。我有一个来自组件的回调,该组件从给定 id 的服务器获取 customer_name。提取工作并且 console.log 正确打印全名,但最后一个 .then 中的 customer_name 未设置,并且函数返回一个空字符串。这是为什么?
// 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;
}
回答by kudlajz
I think you don't understand Promises correctly. The return statement will be called before the Promise is resolved, thus returning empty string.
我认为你没有正确理解 Promises。return 语句将在 Promise 被解析之前被调用,从而返回空字符串。
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);
});
}
or you can use the ES7 approach, using async/await like this
或者你可以使用 ES7 方法,像这样使用 async/await
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);
});
or
或者
async function something() {
const fullName = await tj_customer_name(1);
console.log(fullName);
}
回答by nils
Because fetch is asynchronous and returns a promise, which by its nature can only be observed asynchronously (using .then
).
因为 fetch 是异步的并返回一个 promise,它本质上只能异步观察(使用.then
)。
You should probably just return the promise chain you create in your function and return customer_name
in the last .then
callback of the chain:
您可能应该只返回您在函数中创建的承诺链,并customer_name
在.then
链的最后一个回调中返回:
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
// return the entire promise chain
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) => {
const customer_name = json.first_name.concat(' ').concat(json.last_name);
return customer_name; // return the customer_name here
});
}
// later, use the function somewhere
this.tj_customer_name(21).then((customer_name) => {
// do something with the customer_name
});
PS: Don't forget to add a .catch
handler to handle potential network issues (see: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful)
PS:不要忘记添加.catch
处理程序来处理潜在的网络问题(参见:https: //developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful)