如何从express中的router.post()内的函数代码返回promise promise或reject?

时间:2017-08-03 16:27:02

标签: javascript node.js express promise

以下是我在express(node.js)中的代码

router.post('/example.json', function (req, res) {

  // getFileInfo is a function to return a array
  return getFileInfo(req.body.fileList).then((array) => {

  axios({
    method: 'post',
    url: 'http://localhost:5000/sendTestImage.json',
    data: {
      file: array
    }
  }).then((res) => {
    return Promise.resolve();
  }).catch((err) => {
    return Promise.reject();
  })
});

完成axios调用后,如何返回Promise解决或拒绝并将其返回给客户调用" /example.json"?

1 个答案:

答案 0 :(得分:2)

如果通话成功,您不应该返回任何内容,只需将数据发送给客户端即可。如果出现错误,请设置正确的http响应状态并发送错误:

router.post('/example.json', function (req, res) {
  getFileInfo(req.body.fileList)
    .then(array => {
      return axios({
        method: 'post',
        url: 'http://localhost:5000/sendTestImage.json',
        data: {
          file: array
        }
    })
    .then(data => res.send(data))
    .catch(err => res.status(400).send(err));
});