【问题标题】:Axios wait on endpoint promise before returning dataAxios 在返回数据之前等待端点承诺
【发布时间】:2017-11-23 14:59:36
【问题描述】:

我有一个我调用的 express 端点,里面有一个带有 promise 的函数:

快递服务器:

// endpoint
app.get('/test', function (req, res) {
  res.setHeader('Content-Type', 'application/json')
  let y = 1
  let x = 1
  let bar = foo(x, y)
  res.json({a: bar})
}

const foo = (x, y) => {
  // The promise
  sue.young(y, function(error, output) {
   // do stuff with x and output
   // console.log(output.result) // expected data in console
   // I need to return "output.result"
  })
}

查看:

let axiosClient = axios.create()
axiosClient.interceptors.request.use(async (config) => {
  return new Promise((resolve) => {
    axios.get('/test')
  }).then(res => {
    console.log(res)
  })
    .catch(e => {
      console.log(e)
    })
})

axiosClient.get('/test')
  .then(res => {
    console.log(res)
  })
  .catch(e => {
    console.log(e)
  })

我尝试复制 thisthis 但没有成功;我不断返回一个空对象。

使用 axios,如何等到 promise 完成后再返回任何数据?

【问题讨论】:

    标签: node.js express axios


    【解决方案1】:

    您的问题是您如何在服务器中处理 Promise,而不是在 axios 中。服务器代码不等待 Promise 解决,只是在此之前返回 json。所以你可以做的是返回承诺并等待它。

    // endpoint
    app.get('/test', function (req, res) {
        res.setHeader('Content-Type', 'application/json')
        let y = 1
        let x = 1
        foo(x, y).then(bar => {
            res.json({a: bar});
        });
    }
    
    const foo = (x, y) => {
        // The promise
        return sue.young(y, function(error, output) {
            // do stuff with x and output
            // console.log(output.result) // expected data in console
            // I need to return "output.result"
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      相关资源
      最近更新 更多