I have Promise and do not know how to get string "foo" from it. May be my Promise is incorrect.
const bar = new Promise((res, rej) => res("foo"));
then((result) => {
return result;
});
I have Promise and do not know how to get string "foo" from it. May be my Promise is incorrect.
const bar = new Promise((res, rej) => res("foo"));
then((result) => {
return result;
});
This is how you should do it :
const bar = new Promise((res, rej) => res("foo"));
bar.then((result) => {
console.log(result);
// do whatever you want to do with result
}).catch(err=>console.log(err))
the then
handler is called when the promise is resolved.
The catch
handler is called when the promise is rejected.
const bar = new Promise((res) => res("foo"))
.then((result) => {
console.log(result)
});
You need a period (.
) before the word then
-> .then
then
is a method of Promise
, therefore you need .then
to call the method. then
is not a global function that stand by itself.
When you do:
new Promise((res) => res("foo")).then((result) => ...
any then
will only fire when the Promise is resolved.
The Promise register all the then
methods internally and call them when you do res("foo")
(in your case), so this is why you need a .then
- to register those callbacks to be called when/if the promise is resolved
You're assigning the Promise to the variable bar
. If you want the value you should then
the Promise like the following:
const bar = new Promise((res, rej) => res("foo")).then((result) => {
console.log(result)
});
It's a good practice also to add a catch
statement to handle errors.
Finally, if you're new to Promises there is this free course on Udacity offered by Google which will help you understand Promises better.