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
2
Answers
Use
async/await
to wait for the result. You may need to catch the error.and return the data from
loadDataPesan
function asI see two problems in your code.
First you don’t
await
for theloadDataPesan
to return anything.This means that when
Is called, the promise hasn’t resolved yet. Making the function where this is called an
async
function will allow you to addawait
before the call of the functionloadDataPesan
. This will stop the execution of your code until the promise inloadDataPesan
is resolvedSecondly, you don’t actually return anything in
loadDataPesan
. You do have areturn
statement in the callback of your promise (the function inside thethen
method), but you don’t return the promise at all.To fix that you just need to add a
return
before the call ofaxios