langbung01 icon

promise

langbung01 | PRO | 09/04/18 08:50:29 PM UTC | 0 ⭐ | 606 👁️ | Never ⏰ | []
JavaScript |

1.14 KB

|

None

|

0 👍

/

0 👎

const promise = new Promise((res,rej)=>{
    if(true)
        res("it's pass");
    else
        rej("there re error!!!");
})
 
promise
    .then(res=>res+"!!!")
    .then(res1=>{
        console.log(res1);
    })
    .catch(console.log("error for then 1 and 2"))
    .then(res3=>{
        throw Error;
        console.log(res3);
    })
    .catch(()=>console.log("error for then 3"))
 
const promise1 = new Promise(
    (res,rej) => {
        setTimeout(res,100,"first")
    }
);
 
const promise2 = new Promise(
    (res,rej) => {
        setTimeout(res,1000,"SECOND")
    }
);
 
const promise3 = new Promise(
    (res,rej) => {
        setTimeout(res,2000,"THIRD")
    }
);
 
Promise.all([promise,promise1,promise2,promise3])
    .then((res)=> console.log(res))
    .catch((err)=>console.log(err));
 
const url = [
    "https://jsonplaceholder.typicode.com/posts",
    "https://jsonplaceholder.typicode.com/users",
    "https://jsonplaceholder.typicode.com/albums"
]
 
Promise.all(
    url.map(url=>{  
        return fetch(url).then(res=>res.json());
    })
)
.then(
    res=>{
        console.log(res[0]);
        console.log(res[1]);
        console.log(res[2])
    }
);

Comments