Answer the question
In order to leave comments, you need to log in
Why is the value not returned?
When going to the page, an array of users should be returned, but undefined comes up, which indicates the absence of the value of result , but if you call console.log(), then the value of result is there. I can't figure out what's wrong.
app.get('/users', (req, res) => {
res.send(findOne() + " one");
});
var findOne = (queryObj) => {
let promise = new Promise((resolve, reject) => {
db.collection('users').find(
queryObj
).toArray((err, docs) => {
if (!err) {
resolve(docs);
} else {
reject();
};
})
});
promise.then(result => {
return result;
}, reject => {
return 'error';
});
};
Answer the question
In order to leave comments, you need to log in
Because the value of the arrow function is returned in the promise, the findOne function itself does not return anything.
It should be like this:
app.get('/users', (req, res) => {
findOne().then((result) => {
res.send(result);
})
.catch((e) => {
res.status(500, {
error: e
});
});
});
const findOne = (queryObj) => {
return new Promise((resolve, reject) => {
db.collection('users').find(
queryObj
).toArray((err, docs) => {
if (!err) {
resolve(docs);
} else {
reject(err);
};
});
});
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question