JavaScript Promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let p = new Promise((resolve, reject) => {
let a = 1 + 1;
if (a == 2) {
resolve('Success')
} else {
reject('Failed')
}
})
// Anything inside .then method is going to run after resolve
// .then take a function as parameter
p.then((message) => {
console.log('.then'+message)
}).catch((message) => {
console.log('.catch'+message) // run if promise rejected
})
  • An example of callback
    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 userLeft = false
    const userWatchingCatMeme = false

    function watchTutorialCallback(callback, errorCallback) {
    if (userLeft) {
    errorCallback({
    name: 'User Left',
    message: ':('
    })
    } else if (userWatchingCatMeme) {
    errorCallback({
    name: 'User Watching Cat Meme',
    message:':('
    })
    } else {
    callback('Thumbs up and subscribe')
    }
    }

    watchTutorialCallback((message) => {
    console.log('Success!'+message)
    }, (error) => {
    console.log(error.name+' '+error.message)
    })

The same function with only promise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function watchTutorialPromise(){
return new Promise((resolve, reject) => {
if (userLeft) {
reject({
name: 'User Left',
message: ':('
})
} else if (userWatchingCatMeme) {
reject({
name: 'User Watching Cat Meme',
message:':('
})
} else {
resolve('Thumbs up and subscribe')
}
})
}

watchTutorialPromise().then((message) => {
console.log('Success!'+message)
}).catch((error) => {
console.log(error.name+' '+error.message)
})

Promise.all

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const recordVideoOne = new Promise((resolve, reject) => {
resolve('Video 1 Recorded')
})
const recordVideoTwo = new Promise((resolve, reject) => {
resolve('Video 2 Recorded')
})
const recordVideoThree = new Promise((resolve, reject) => {
resolve('Video 3 Recorded')
})

Promise.all([
recordVideoOne,
rocordVideoTwo,
recordVideoThree
]).then((messages) = > { // messages is an array of all messages
console.log(messages)
})

// All the three functions are run at the SAME time

Promise.race

Promise.race will return the fastest function, which is a single message in this case

1
2
3
4
5
6
7
Promise.race([
recordVideoOne,
recordVideoTwo,
recordVideoThree
]).then((message) => { // Only get one return value
console.log(message)
})