![]() |
星星上的麻辣香锅 · 这不是小电驴,而是真正的电动摩托 - 42 号车库· 4 月前 · |
![]() |
坚强的啄木鸟 · 第54话 - 老夫老妻重返青春 - 包子漫画· 1 年前 · |
![]() |
眼睛小的芒果 · 重庆市沙坪坝区人民政府· 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