2

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;
});
Festina
  • 327
  • 3
  • 17

3 Answers3

3

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.

programoholic
  • 4,830
  • 5
  • 20
  • 59
  • 1
    Can you assume the promise will resolve instantly (like a normal function) and attempt to obtain the result, something like `bar.result`, be it "foo" or undefined (for when it didn't resolve yet)? – Benur21 Jun 16 '22 at 22:30
2

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

vsync
  • 118,978
  • 58
  • 307
  • 400
1

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.

Ahmad Alfy
  • 13,107
  • 6
  • 65
  • 99