Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Understanding Promise Behavior Through Practical Examples

Tech 2

Example 1

Key Concept: A Promise can only change its state once

const myPromise = new Promise((fulfill, reject) => {
    reject();
    fulfill();
});

myPromise.then(
    () => console.log('Success'),
    () => console.log('Failure')
);

Output:

Failure

Example 2

Key Concept: resolve() and reject() do not terminate code eexcution

const promiseInstance = new Promise((resolve, reject) => {
    console.log(1);
    resolve();
    console.log(2);
});

promiseInstance.then(() => {
    console.log(3);
});

Output:

1
2
3

Example 3

Key Concepts:

  1. Promise.resolve() is equivalent to new Promise((resolve, reject) => resolve(value))
  2. When no error occurs, catch() callback are not invoked
Promise.resolve(1)
    .then(result => 2)
    .catch(error => 3)
    .then(result => console.log(result));

Output:

2

Example 4

Key Concept: Returning a normal valuee from catch() transitions to the next success handler

Promise.resolve(1)
    .then(value => value + 1)
    .then(value => { throw new Error('Custom Error') })
    .catch(() => { throw 'error message' })
    .then(value => value + 1)
    .then(value => console.log(value))
    .catch(error => console.error(error));

Output:

error message

Example 5

Key Concept: Code after await exceutes similarly too promise.then(() => { ... })

async function firstAsync() {
    console.log('firstAsync start');
    await secondAsync();
    console.log('after await');
}

async function secondAsync() {
    console.log('secondAsync');
}

console.log('script start');
setTimeout(() => {
    console.log('timeout');
}, 0);

firstAsync();

new Promise((resolve) => {
    console.log('promise init');
    resolve();
}).then(() => {
    console.log('promise then');
});

console.log('script end');

Output:

script start
firstAsync start
secondAsync
promise init
script end
after await
promise then
timeout

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.