Axios在返回数据之前等待端点承诺

编程入门 行业动态 更新时间:2024-10-28 09:21:16
本文介绍了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在返回数据之前等待端点承诺

本文发布于:2023-11-26 15:06:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634219.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   Axios

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!