Skip to content

How to implement a Promise that is Promises/A+ compliant using vanilla JavaScript.

License

Notifications You must be signed in to change notification settings

jeantimex/how-to-implement-promise

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

How to Implement Promise

Build Status

Implement a Promise that is Promises/A+ compliant using vanilla JavaScript.

cover

Example Usage

const Promise = require("./promise");

Basic

Promise.resolve(233)
  .then()
  .then(function(value) {
    console.log(value);
  });

setTimeout

function delay(ms) {
  return new Promise(function(resolve) {
    setTimeout(resolve, ms);
  });
}

(async function print() {
  console.time("setTimeout");
  await delay(1000);
  console.timeEnd("setTimeout");
})();

Promise.all

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, "foo");
});
const promise4 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 200, "bar");
});

Promise.all([promise1, promise2, promise3, promise4]).then(function(values) {
  console.log(values);
});

Promise.race

const promise1 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 500, "one");
});

const promise2 = new Promise(function(resolve, reject) {
  setTimeout(resolve, 100, "two");
});

Promise.race([promise1, promise2]).then(function(value) {
  console.log(value);
});

Test with Promise/A+ specs

npm run test

unit-tests

Note: The Promises/A+ compliance test suite can be found here.

References

  1. Promise/A+ Specs
  2. MDN - Promise
  3. Implementing Promise
  4. Implementing promises from scratch
  5. Promises, Next-Ticks and Immediates
  6. 深入理解 Promise (中)
  7. 解读Promise内部实现原理

About

How to implement a Promise that is Promises/A+ compliant using vanilla JavaScript.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published