考研的松树 · 首部《柳叶刀倒计时中国报告》发布...· 1 年前 · |
风流的针织衫 · iPhone ...· 1 年前 · |
粗眉毛的牛排 · 黑胶唱片制作过程_黑胶唱片制作过程是全模拟的 ...· 1 年前 · |
稳重的匕首 · 【德克西(DEKEXI)台上式净水器】净水器 ...· 1 年前 · |
我试图检索数据,但我无法返回它,只能在控制台中看到它,这是一个简单的axios get函数,但由于某些原因,即使在使用async/await之后,我仍然得到了承诺。
我的目标是将数据保存到内存中。
任何帮助都将不胜感激
let fetchTodo = async () => {
await axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log(res.data))
.then(res => { return res })
.catch(err => console.log(err))
console.log("TEST: ", fetchTodo())
发布于 2021-08-26 19:36:25
Asycn函数总是返回一个promise,要从fetchTodo函数获取数据,您需要创建另一个等待fetchTodo()返回结果的异步函数。如果您正在使用react,则可以在fetchTodo函数的.then链中使用状态并更新状态。
发布于 2021-08-26 19:53:56
async/await
语法意味着函数将返回一个
Promise
。
如果你想返回值,你可以这样做:
let fetchTodo = async () => {
try {
const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
return res;
} catch (error) {
console.log(error);
// For the folowing code to work, it must be placed inside a async function as well
const res = await fetchTodo();
console.log(`Test: ${res.data}`);
// If it's a Top level call, use the folowing code
const res = fetchTodo().then( res => {
const data = res.data;
// The rest of your code goes here.
// ...
// ...
// ...
}).catch( error => {
console.log(error);
});
有关它的更多信息,请访问: How can I use async/await at the top level?
发布于 2021-08-26 22:07:16
Asycn函数总是返回一个promise。为了获取或保存数据,您需要从
.then()
函数中获取数据。您可以在这里查看示例。希望它能对你有所帮助。
let fetchTodo = async () => {
await axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(res => console.log(res.data))
.then(res => {
// here you can performance your task, save data, send
// response or anything else
考研的松树 · 首部《柳叶刀倒计时中国报告》发布... 1 年前 |