A
A
Andrey Mollinzz2018-05-08 21:45:10
JavaScript
Andrey Mollinzz, 2018-05-08 21:45:10

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';
  });
};

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
Jumandjilos, 2018-05-08
@keAgzz

try return new Promise at the beginning of writing

I
Igor Koch, 2018-05-08
@amux

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 question

Ask a Question

731 491 924 answers to any question