如何在调用函数时将获取请求放入函数中并等待返回值



我使用的是react native、mongo DB和node js,我需要创建一些数据库函数,并将它们放在一些模块中,以便随时重用它们。为了从mongo数据库中获取数据,我使用了返回promise的fetch()函数。因此,对于我创建的所有没有返回值的函数,我使用了.then,并且没有遇到任何问题。另一方面,当我在fetch().then()函数中返回一个值并使用这个返回值时,我会得到未定义的值。我用于该函数的代码看起来像:

export const getUsers = () => {
//I cannot use this function because of returning a promise
fetch("http://1jjsd12zaws.ngrok.io/database/", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
res.json();
})
.then((data) => {
return JSON.stringify(data);
});
};

然后,当我尝试运行以下代码时:

let users=getUsers();
console.log(users);

它打印undefined

我认为console.log(users)getUsers()返回其值之前运行。但我不知道为什么会发生这种情况,我希望它等待getUsers()执行,然后完成它的工作。

  • 您需要在getUsers中返回fetch(..)(这就是您获得undefined的原因(
  • 您还需要在第一个then中返回res.json()
  • 由于getUsers返回Promise,因此需要使用.then(或async/await(来访问Promise值:getUsers().then(users => {...})

const getUsers = () => {
return fetch('http://1jjsd12zaws.ngrok.io/database/', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
return res.json();
})
.then(data => {
return JSON.stringify(data);
});
};
getUsers().then(users => console.log(users))

Async和await应该涵盖这一点。MDN文档上的例子比我能更好地解释它,应该适用于您的用例。

最新更新