Axios wait on endpoint promise before returning da

2019-08-17 18:06发布

问题:

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