Axios在返回数据之前等待端点承诺 [英] Axios wait on endpoint promise before returning data

查看:538
本文介绍了Axios在返回数据之前等待端点承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个明确的端点,它具有一个内部带有promise的函数:

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

查看:

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.

使用axios,我如何才能等到诺言完成之后再返回任何数据?

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

推荐答案

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

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

这篇关于Axios在返回数据之前等待端点承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆