英文:
AXIOS in express js return Promise { undefine }
问题
Here is the translated content:
我正在学习 Express.js 和 Axios。
我创建了一个名为 "utils" 的文件夹,并放置了 axios.js 文件:
const axios = require('axios');
loadDataPesan = async function (opts) {
axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
})
.then(function (response) {
console.log(response.data.datas) // 通常会显示正确的数据
return response.data.datas; // 这里是我的问题,当我返回数据时,它总是 Promise { }
})
.catch(function (error) {
return error;
});
}
module.exports = { loadDataPesan };
这是我的 app.js 文件:
const express = require('express');
const expressLayout = require('express-ejs-layouts');
const { loadContact } = require('./utils/contact');
const { loadDataPesan } = require('./utils/axios');
const app = express();
const port = 8899;
app.set('view engine', 'ejs');
app.use(expressLayout);
// 内置中间件
app.use(express.static('public'));
app.get('/contact', (req, res) => {
const contacts = loadContact();
const dataaxio = loadDataPesan("SUBS", "912830123");
console.log(dataaxio); // **这里是我的问题,响应总是 Promise { }**
res.render('contact', {
layout: 'layouts/main-layout',
title: 'Halaman Contact',
contact: contacts,
});
})
感谢您提前帮助,如果有人能帮助我。
我尝试在函数中使用 async,但结果仍然相同,我还尝试使用回调响应,结果也相同。
英文:
i new learn expressjs and axios
i create a folder utils and place the
axios.js file
const axios = require('axios');
loadDataPesan=async function(opts){
axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
})
.then(function (response) {
console.log(response.data.datas) // ITS NORMALLY SHOW THE CORRECT DATA
return response.data.datas; // HERE MY PROBLEM, WHEN I RETURN IT DATA always Promise { }
})
.catch(function (error) {
return error;
});
}
module.exports = { loadDataPesan };
here my app.js files
const express = require('express');
const expressLayout = require('express-ejs-layouts');
const { loadContact } = require('./utils/contact');
const { loadDataPesan } = require('./utils/axios');
const app = express();
const port = 8899;
app.set('view engine', 'ejs');
app.use(expressLayout);
// BUILTIN MIDDLEWARE
app.use(express.static('public'));
app.get('/contact', (req, res) => {
const contacts = loadContact();
const dataaxio = loadDataPesan("SUBS","912830123");
console.log(dataaxio); // **HERE MY PROBLEM RESPONSE ALWAYS Promise { }**
res.render('contact', {
layout: 'layouts/main-layout',
title: 'Halaman Contact',
contact:contacts,
});
})
thanks you in advance if someone can help me
i try given async in function but it same also i try callback response its same also
答案1
得分: 1
Use async/await
to wait for the result. You may need to catch the error.
app.get('/contact', async (req, res) => { <-- convert it to async function
const contacts = loadContact();
const dataaxio = await loadDataPesan("SUBS","912830123"); <-- await for response
console.log(dataaxio);
res.render('contact', {
layout: 'layouts/main-layout',
title: 'Halaman Contact',
contact: contacts,
});
})
And return the data from loadDataPesan
function as
loadDataPesan = async function(opts) {
try {
const response = await axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
});
console.log(response.data.datas); // Log the correct data
return response.data.datas; // Return the data
} catch (error) {
console.error(error);
throw error; // Throw the error to be caught by the caller
}
}
英文:
Use async/await
to wait for the result. You may need to catch the error.
app.get('/contact', async (req, res) => { <-- convert it to async function
const contacts = loadContact();
const dataaxio = await loadDataPesan("SUBS","912830123"); <-- await for response
console.log(dataaxio);
res.render('contact', {
layout: 'layouts/main-layout',
title: 'Halaman Contact',
contact:contacts,
});
})
and return the data from loadDataPesan
function as
loadDataPesan = async function(opts) {
try {
const response = await axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
});
console.log(response.data.datas); // Log the correct data
return response.data.datas; // Return the data
} catch (error) {
console.error(error);
throw error; // Throw the error to be caught by the caller
}
}
答案2
得分: 0
I see two problems in your code.
First, 你没有等待 loadDataPesan
返回任何内容。
这意味着当
console.log(dataaxio);
被调用时,承诺尚未解决。将调用函数 loadDataPesan
之前添加 await
将使代码在 loadDataPesan
中的承诺解决之前停止执行。
const contacts = loadContact();
const dataaxio = await loadDataPesan("SUBS", "912830123");
// ...
其次,在 loadDataPesan
中实际上没有返回任何内容。虽然你在承诺的回调中有一个 return
语句(在 then
方法内的函数中),但你根本没有返回该承诺。
要修复这个问题,你只需要在调用 axios
之前添加一个 return
。
const axios = require('axios');
loadDataPesan = async function (opts) {
return axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
})
// ...
}
module.exports = { loadDataPesan };
英文:
I see two problems in your code.
First you don't await
for the loadDataPesan
to return anything.
This means that when
console.log(dataaxio);
Is called, the promise hasn't resolved yet. Making the function where this is called an async
function will allow you to add await
before the call of the function loadDataPesan
. This will stop the execution of your code until the promise in loadDataPesan
is resolved
async (req, res) => {
const contacts = loadContact();
const dataaxio = await loadDataPesan("SUBS","912830123");
// ...
Secondly, you don't actually return anything in loadDataPesan
. You do have a return
statement in the callback of your promise (the function inside the then
method), but you don't return the promise at all.
To fix that you just need to add a return
before the call of axios
const axios = require('axios');
loadDataPesan=async function(opts){
return axios.get('localhost/getData', {
params: {
opt: opts,
nis: "123123",
}
})
// ...
}
module.exports = { loadDataPesan };
答案3
得分: 0
Here's the translated content:
- 在 axios.js 文件中,这一行
loadDataPesan=async function(opts)
你没有使用建议使用的 const 关键字。要么这样写 ->
const loadDataPesan = async function(opts) {
// 函数体
};
要么这样写 ->
async function loadDataPesan(opts) {
// 函数体
}
- 在导出单个函数时,应像这样导出 ->
module.exports = loadDataPesan;
- 正如其他答案中所指出的,如果你在函数顶部使用了 async 关键字,应使用 async/await 语法。最好的错误处理实践是将代码放在 try-catch 块中。以下是如何重构代码的示例,我使用了 express 模块的 Router 方法 进行路由。你可以在 这里 学习更多关于 express.Router 部分的内容。
axios.js 文件
const axios = require("axios");
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
const resp = await axios.get(
"a_url_path"
);
res.send(resp.data);
} catch (error) {
res.send(error.message);
}
});
module.exports = router;
app.js 文件 ->
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axiosFile = require("./axios");
//其他代码....
app.use("/data", axiosFile);
//其他代码...
app.listen(5000, () => {
console.log("监听端口 5000");
});
英文:
There are a few problems that I can see ->
- In the axios.js file, this line
loadDataPesan=async function(opts)
you are not using the const keyword which is recommended. Either write this
way ->
const loadDataPesan = async function(opts) {
// Function body
};
or this way ->
async function loadDataPesan(opts) {
// Function body
}
- When exporting a single function, export like this ->
module.exports = loadDataPesan;
- As pointed out in other answer, if you are using using async keyword at the top of a function, use async/await syntax. It is also a good practice to wrap the code in a try-catch block for better error handling. Here is an example of how you can restructure your code, I used the Router method of express module for routing. You can learn more about it here under the express.Router section.
axios.js file
const axios = require("axios");
const express = require("express");
const router = express.Router();
router.get("/", async (req, res) => {
try {
const resp = await axios.get(
"a_url_path"
);
res.send(resp.data);
} catch (error) {
res.send(error.message);
}
});
module.exports = router;
app.js file ->
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axiosFile = require("./axios");
//other code....
app.use("/data", axiosFile);
// other code...
app.listen(5000, () => {
console.log("Listening on port 5000");
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论