Saturday 2 March 2019

How to Define a Promise and call it in JavaScript

/*
How to define promises

1. create a new instance of promise
const myP = new Promise()

2. Promise constructor has a single arg, which is again a function
const myP = new Promise(function(){

})

3. Now this function has two agrs
const myP = new Promise(function(resolve, reject){

})

4. Now this function is called right away, where we can make http request or db connection and data fetch. Lets add a async settimeout
const myP = new Promise(function(resolve, reject){
    setTimeout(()=>{
        console.log('2 sec wait')
    },2000)
})


5. Pass a either reject or resolve into async call

const myP = new Promise(function(resolve, reject){
    setTimeout(()=>{
        resolve('2 Sec Time Over')
    },2000)
})


6. access myP using method then, which has 2 args [which are functions],  first is called for resolve, and 2nd is called for reject

myP.then(
    function(data){console.log(data)},
    function(err){console.log(err)}
    )

*/

Code:

const myPromise = new Promise(function(resolve, reject){
    setTimeout(() => {
        resolve("This is resolved")
    }, 2000);
})

myPromise.then(
    function(data){
    console.log(data)
    },
    function(err){
    console.log(err)    
    }       
)


No comments:

Post a Comment