# Promises

A Promise, as the name implies is something that Promises a return value. We just don't know when we will get the reply. It could be fulfilled or it could fail to be fulfilled. Either way you will get an answer.

A Promise that is fulfilled and returns what we want is called resolved.

A Promise that is not fulfilled is called rejected.

The syntax for a Promise is just like thee fetch method. (That is because a fetch IS a Promise.). when you call fetch() you are actually given a Promise object which eventually will give you a response object and call the first then method or it fails and calls the catch method.

let p = new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000, 'hello');
  //wait for two seconds and then call the resolve
});

p.then(function(response) {
  //response will be  the value returned by the resolve method inside the Promise
  console.log(response);
  //it will output 'hello'
});

p.catch(function(err) {
  //if the reject method was called first from the  Promise
  //then this catch method's function would  run.
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Back to Week 9 main page

Last Updated: 11/1/2020, 2:12:38 PM