How to handle "Promise { <pending> }" in javascript - javascript

I have this function in javascript
const getData = async() => {
try {
const serviceResponse = await someService("userId")
return serviceResponse
} catch (error) {
console.log(error);
}
}
const data = getData()
console.log(data)
Whenever I am running this I am getting this in console
Promise { <pending> }
But when I am print data in the function itself I am getting the desired value
const getData = async() => {
try {
const serviceResponse = await someService("userId")
console.log.(serviceResponse)
} catch (error) {
console.log(error);
}
}
getData()
The following function is what I am importing from defined in another another
exports.someService = async(date,locationId,workerType) => {
const value = await Attendance.find({})
return value
}
Please can someone explain what is happening ?

you need to await the promise from getData() too -
const data = await getData()

Related

Axios put return undefined [React JS + Axios]

Hi all im doing an axios put to update my data. However im getting an undefined response. Thank you in advance
function that call the Axios:
export function exUpdateMovie(movie) {
Axios.put(baseURL + "/api/update", {
movieName: movie.movieName,
movieReview: movie.movieReview,
id: movie.id,
})
.then((response) => {
// console.log(response);
return response;
})
.catch((e) => {
console.log(e);
return e;
});
}
function in app.js that calls the exUpdateMovie(movie) function:
const handleUpdateMovie = (movie) => {
console.log("UpdateMovie Passed!");
try {
const res = exUpdateMovie(movie);
alert(res?.data);
} catch (error) {
console.log(error);
}
};
Output when I alert my response is:
undefined
SETTLE:
need to add async and await at the handleUpdateMovie
need to return the Axios by doing return Axios.put()
Cheers mate for helping me. Thanks alot
Yes because your api call is returning a promise where you need to wait until the promise execution completes so make your function async and wrap the API call with await.
export async function exUpdateMovie(movie) {
const result = await Axios.put(baseURL + "/api/update", {
movieName: movie.movieName,
movieReview: movie.movieReview,
id: movie.id,
})
return result
}
const handleUpdateMovie = async (movie) => {
console.log("UpdateMovie Passed!");
try {
const res = await exUpdateMovie(movie);
alert(res?.data);
} catch (error) {
console.log(error);
}
};
Because exUpdateMovie doesn't return anything. Return the Promise:
export function exUpdateMovie(movie) {
return Axios.put(/* all your Axios code */);
}
Then when consuming the result, treat it as a Promise:
exUpdateMovie(movie).then(res => {
alert(res?.data);
});

React native async function returns empty object

I am trying to get a token stored in securestore, and pass it to url. When I try to call the api the value of the token is just an empty object. I am able to see the value t here if I alert in readToken function. Its not passed to getMovies function.
const readToken = async () => {
try {
const storedToken = await SecureStore.getItemAsync('token');
return storedToken;
} catch (e) {
console.log(e);
}
};
const getMovies = async () => {
try {
let url = 'https://someurl.de/api/getschichten/?userid=9&token='+readToken();
alert(url);
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
So, I changed my code according to kipnodels. Here's my code that works
let myToken = await readToken();
let url = 'https://esm.nvii-dev.de/api/getschichten/?userid=9&token='+myToken;

Promise pending, fulfilled not returning

Trying to display data from a json.
When I run my functions on the console, it shows:
PromiseĀ {} and [[PromiseState]]: "fulfilled"
But not actually returning anything.
getJobs = async () => {
try{
response = await fetch("./data.json");
const data = await response.json();
return data;
} catch(error){
console.log('Error getting data', error)
}
}
renderJobs = async () => {
const jobs = await getJobs();
const view = `
<div class='card-company'>
${jobs.map(companyName => `
<p>${companyName.company}</p>
`).join('')}
</div>
`
return view
}
I have all the p tags I need inside the property [[PromiseResult]] but nothing displaying in the document.
I have not been able to find anything like this, also if there's anything to improve in this snippet, I appreciate the feedback.
Thank you.
Since these are async functions, you need to use await to get their final return value.
To log the HTML string, you can use console.log(await renderJobs());, and wherever you are running renderJobs() in your code, you will need to use await to get the HTML string as well.
Using console.log(renderJobs()); will return the promise pending message you described because async functions return a promise, not the result of the promise. Using await returns the fulfilled value of the promise it is used on.
Looks like an improper template to me. I'm not seeing a use for it in this case, anyways. Should be more like:
const M = tag=>document.createElement(tag);
const renderJobs = async () => {
const jobs = await getJobs(), frag = document.createDocumentFragment();
let d;
for(let o of jobs){
d = M('div'); d.className = 'card-company'; d.textContent = o.company;
frag.appendChild(d);
}
// you could append frag here or return and append later
return frag;
}
try it
getJobs = () =>
new Promise((resolve) => {
fetch("./data.json").then((data) => {
resolve(data);
});
});
renderJobs = async () => {
const jobs = await getJobs();
const view = (
<div class="card-company">
${jobs.map((companyName) => <p>${companyName.company}</p>).join("")}
</div>
);
return view;
};
I see an issue with how you are not handling an error. You need to return reject or throw an error. Otherwise, the promise will never be resolved
getJobs = async () => {
try {
const response = await fetch('./data.json')
const data = await response.json()
return data
} catch (error) {
console.log('Error getting data', error)
return Promise.reject(error)
}
}
renderJobs = async () => {
let jobs = []
try {
jobs = await getJobs()
} catch(error) {
console.log('Error getting data', error)
}
const view = `
<div class='card-company'>
${jobs
.map(
(companyName) => `
<p>${companyName.company}</p>
`
)
.join('')}
</div>
`
return view
}

how to return multiple values from an asynchronous function to use in another function

I am getting login and password values in an asynchronous function and returning using destructuring. But when I try to use the data in another function, it outputs - undefined. Help please. In what the problem
async function authWithLoginAndPassword() {
const response = await fetch('');
const data = await response.json();
const logUser = data[0].login;
const passwordUser = data[0].password;
return { logUser, passwordUser }
}
submit.addEventListener('click', () => {
let register = authWithLoginAndPassword();
console.log(register.logUser, register.passwordUser)
})
All async functions return a promise that resolves to whatever value you return from that function. So, when you call authWithLoginAndPassword(), you have to use either .then() or await to get the resolved value from the promise that the function returns:
submit.addEventListener('click', async () => {
try {
let register = await authWithLoginAndPassword();
console.log(register.logUser, register.passwordUser)
} catch(e) {
// catch errors
console.log(e);
}
});
or
submit.addEventListener('click', () => {
authWithLoginAndPassword().then(register => {
console.log(register.logUser, register.passwordUser)
}).catch(err => {
console.log(err);
});
});

What is the correct way to export an Async function module?

I have a file asyncAwait.js that has a simple function:
async function doStuff() {
return(`Function returned string.`);
}
module.exports.doStuff = doStuff;
In another module, testing.js, I invoke and all works as expected:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs "Function returned string." to the console.
All good.
However, if I use axios in asyncAwait.js:
const axios = require(`axios`);
async function doStuff(parameter) {
const url = `https://jsonplaceholder.typicode.com/posts/1`;
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
console.log(data);
} catch (error) {
console.log(error);
}
};
return(getData(url));
}
module.exports.doStuff = doStuff;
Then in testing.js:
var functions = require(`./functions`);
(async () => {
const test = await functions.asyncAwait.doStuff();
console.log(test);
})();
This logs undefined.
Why does the function call return undefined in the second example?
In your example getData has no return. In this case your function will implicitly return undefined. To fix it you could change that function to the following:
const getData = async url => {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
return error
}
};
module.exports.doStuff = doStuff;
May I suggest you :
module.exports=doStuff;
Or
exports.doStuff
and maybe but not sure what you're trying to achieve
replace
return(getData(url));
by
return(()=>{return getData(url)});

Categories

Resources