This page looks best with JavaScript enabled

Ways to a Promise in Javascript

 ·   ·  ☕ 3 min read

You already know that promises enable us to carry out asynchronous transactions. How do you implement in your own programs?

I assume you already know what promises do in Javascript](/promises-javascript) and how event driven programming works :)

Javascript promise is an object. So, Promise should be as easy as using an object. As it is typical in Javascript, everything seems easy, and then stacks up all the different ways to amaze and confuse mortals.

Promise constructor

A bare-bones promise constructor looks like this..

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
let promiseToLog = new Promise(function(resolve, reject) {
  console.log("the dawn of a promise");
  setTimeout(function() {
    resolve("a promise fulfilled.. after timeout");
  }, 300);
  console.log("timer may not be complete; next statement is executed");
});

console.log("promise initialized");

promiseToLog.then(function(val) {
  console.log(val);
});

promiseToLog.catch(function(e) {
  console.log("error", e);
});

console.log(promiseToLog);

/* output
the dawn of a promise
timer may not be complete; next statement is executed
promise initialized
Promise { <pending> }
a promise fulfilled.. after timeout
*/

Here’s the sequence of events -

  1. promiseToLog initialized. First log statement printed
  2. setTimeOut executed. Timer starts. Promise will only be resolved when timer’s done
  3. timer running. Moved to next statement to print ‘timer may not be complete…’
  4. timer running. promiseToLog is initialized now. Moved to next statement to print ‘promise initialized’
  5. timer running. promise resolver or error not called - yet. Moved to next statement to print object. The object says Promise {<Pending>} since the promise is not yet resolved
  6. at last timer completes. Call resolver with a message ‘a promise fulfilled..’
  7. function in promiseToLog.then() is executed and the input message ‘a promise fulfilled..’ is printed

Well, that’s about it - you can now claim to be a promising person. Everything else is more sugar.

async - await

Async await is syntactic sugar on top of promises.

Oh.. before you say - yes, I have seen a million posts on the Internet that talk about how async/await blows promises out of water. That is confusing to me to say the least. Why did promise get in the water? Why is async/await pumping air at anything?

Any way, async/await is syntactic sugar for a promise. All the stuff you saw in the previous paragraph - you can in fact “blow the stuff out of the water” and use the newer syntax. The async/ await syntax does not jump around but follows a more traditional approach to the kind of top-down programming we like.

Let us try something more practical this time rather than a timeout. We will fetch a todo from a server. fetch returns a promise and we are awaiting for the promise to resolve before moving to the next statement. await works only within the context of an async function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

const fetch = require("node-fetch");

console.log("start something");
doSomething();
console.log("end something");

async function doSomething() {
  console.log("something initiated");
  const fetchTodo = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  console.log("fetchTodo: ", fetchTodo);

  console.log("fetch complete");
}

console.log("era of something over; now there is nothing");

/* output
start something
something initiated
end something
era of something over; now there is nothing
fetchTodo: {.. }
fetch complete

The anatomy of async/await is similar to a promise because it is a promise underneath. However, you can see that we don’t need to write confusing functions everywhere.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things