我的目标是在react应用程序中从MongoDB地图集获取数据。即使在用axios.get()编写了.then和.catch之后,我也得到了一个未解决的承诺。
我的代码:
const entry = axios.get('http://localhost:3001/user')
.then(res=>{
console.log(res.data)
return res.data;
})
.catch(err=>{console.log("Error: "+err)})
console.log(entry);上面的代码片段具有以下输出
Promise {<pending>}
(5) [{…}, {…}, {…}, {…}, {…}]在这里,console.log(res.data)给了我数组,而console.log(entry)给了我一个未决的承诺。
以下是我从MongoDB地图集检索数据时的nodejs代码
const express = require('express');
const Route = express.Router();
const Note = require('../models/note');
Route.get('/', async(req, res)=>{
await Note.find()
.then(notes=>res.send(notes))
.catch(err=>res.send("Error: "+err))
})
module.exports = Route;发布于 2021-04-05 04:06:35
这是javascript事件循环的一部分。事件循环获得它的名称,因为它同步地等待消息的到达。它实际上是在监控回调队列,所以如果调用堆栈是空的,它将从回调队列中获取第一个事件,并将其推送到调用堆栈,调用堆栈将有效地运行它。
因此,让我们分解您的代码,并尝试了解发生了什么:
const entry = axios.get('http://localhost:3001/user') // 1
.then(res=>{ // 2
console.log(res.data) // 3
return res.data;
})
.catch(err=>{console.log("Error: "+err)})
console.log(entry); // 4你可以在这里了解更多:
https://stackoverflow.com/questions/66945219
复制相似问题