Reputation: 57
I'm trying to access the result from an async function from one file in another file (say index.js).
test.js
const preMovie = async () => {
const promiseTickets = new Promise((resolve, reject) => {
console.log("abcde");
resolve('ticket is here')
});
let ticket = await promiseTickets;
return ticket;
}
preMovie().then((m) => console.log(m));
index.js
//access the value of ticket here
My goal is to export the value inside ticket only when it has completed its task. I don't want to export an undefined value. I have tried my hand with different solutions, but either they are too complicated for me to understand or didn't blend with what I was looking for.
Upvotes: 0
Views: 378
Reputation: 370929
You can export a Promise that resolves to ticket
's value:
// test.js
const preMovie = async () => {
const promiseTickets = new Promise((resolve, reject) => {
console.log("abcde");
resolve('ticket is here')
});
let ticket = await promiseTickets;
return ticket;
}
const moviePromise = preMovie();
//export default moviePromise;
// main.js
//import moviePromise from './test.js';
moviePromise
.then(ticket => console.log(ticket));
Uncomment the import
and export
statements when using them in your actual code, of course. Another option would be to export the function itself, calling it and calling .then
on it, if there's a possibility of the function being needed to be called more than once, or if controlling its timing is important.
Upvotes: 1