DEV Community

Brian
Brian

Posted on

Javascript Promises

Was working with javascript promises in a project and at one point I needed to know how .then worked with having a promise inside of it.

Here is what I found promises have to resolve before the .then will fire. If you want to have a promise inside a then you can do that but it needs to be a resolved promise. Here is some example code.

new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000);

}).then(function(result) {

  alert(result); // 1

  return new Promise((resolve, reject) => { // (*)
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) { // (**)

  alert(result); // 2

  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(result * 2), 1000);
  });

}).then(function(result) {

  alert(result); // 4

});

Also here is some documentation on promises from javascript.info https://javascript.info/promise-chaining

Top comments (0)