Axios wait on endpoint promise before returning data

末鹿安然 提交于 2020-01-07 05:07:26

问题


I have an express endpoint that I call that has a function with a promise inside:

Express Server:

// 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"
  })
}

View:

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

I've tried to replicate this and this but no luck; I keep getting an empty object returned.

With axios, how can I wait until the promise is finished before returning any data?


回答1:


Your problem is how you are treating the Promise in the server, not in axios. The server code is not waiting to the Promise to resolve, is just returning the json before that. So what you can do is return the promise and wait for it.

// 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"
    })
}


来源:https://stackoverflow.com/questions/44663680/axios-wait-on-endpoint-promise-before-returning-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!