I am learning promise in JavaScript but I don't understand why my function doesn't return the right value.
This is my function:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
}
console.log(promise());
If I run the code I get undefined.
I think the problem is that the console.log is executed before the value of the .then is returned.
Can somebody please help me to solve this problem and maybe explain the problem? :)
Thanks for every answer.
Two things:
You must return the promise p from within the promise function.
You must await the result of the promise returned by the function before you can access its fulfilled value:
function promise() {
let p = new Promise((resolve, reject) => {
return resolve(["a", "random", "array"]);
});
p.then((response) => {
return response;
}).catch((error) => {
return error;
});
// 1. Return the promise from the function:
return p;
}
// 2. Await the result before using it:
promise().then((result) => {
console.log(result);
});
You said you're learning about promises. Async/await makes all of this much easier:
<script type="module">
// Top level await is available in ES modules
async function promise () {
try {
return ["a", "random", "array"];
}
catch (exception) {
return exception;
}
}
const result = await promise();
console.log(result);
</script>