我在 react.js 项目中有简单的获取:
export function getUserById(id) {
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json','Access-Control-Allow-Origin':'http://localhost:9000' },
mode: 'no-cors',
};
var res = fetch("http://localhost:9000/user/"+id);//there should be a lot of strange lambdas..
return res;
}
我在其他文件中使用这个函数:var user = getUserById(userStr);
//some code
//more code
var email=user.mail;
var id = user.id;
不幸的是- res
永远是 promise 。我不觉得函数式编程和 react ,但我需要这样做。我知道应该有一些 lambda 表达式,但我不知道如何编写它们。如您所见,我需要从返回的 JSON 中获取电子邮件和 ID。提前致谢。
最佳答案
您需要await
获取调用。
见 this example on MDN .
export async function getUserById(id) {
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json','Access-Control-Allow-Origin':'http://localhost:9000' },
mode: 'no-cors',
};
var res = fetch("http://localhost:9000/user/"+id);//there should be a lot of strange lambdas..
return res;
}
var user = await getUserById(userStr);
//some code
//more code
var email=user.mail;
var id = user.id;
编辑:您不需要 await
fetch 调用,你只需要 await getUserById(userStr)
.
关于reactjs - 如何在 fetch 中正确编写 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68968900/