Asynchronous JavaScript Promises
Creation
We rarely need to create custom promises as most of the asynchronous operations we need already have functions and method that return promises.
We can create new promises by passing the constructor a function. The constructor will give us the resolve and reject function which we can use to transition from the pending state to the fulfilled or failed state.
const slowMultiplication = (x, y) => {return new Promise((resolve, reject) => {setTimeout(() => {resolve(x * y)}, 1000)})}const returnedPromise = slowMultiplication(2, 3)returnedPromise.then(result => {console.log(`result = ${result}`)})console.log("Hi there")
In the example above the function slowMultiplication returns a
Promise. The promise resolves after one second thanks to the
setTimeout method. Try copying the code, paste it into your web
developer console and run it.