JS promises Flashcards

1
Q

How to write a promise

A
const doWork = new Promise((resolve,reject)=>{
    const a = 1;
    if(a === 1){
        setTimeout(()=>{
            resolve([3,4,5])
        },5000)
    }else{
        setTimeout(()=>{
            reject("Oops")
        },5000)
    }

});

doWork.then((result)=>{
    console.log(result)
}).catch((error)=>{
    console.log(error)
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When does a promise stop running?

A

When either resolve or reject is called. resolve and reject acts like a return statement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do promises work?

A

When a promise is called, it is considered pending. Once the pending promise resolves it is considered fullfilled. When it is not resolved it is considered rejected.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is promise chaining?

A

Chaining multiple promises together

Avoids callback hell or nested and duplicate code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to chain promises?

A
const sum = (x,y)=>{
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve(x + y)
        },3000)
    })
};
sum(5,5).then((result)=>{
    return sum(result,5)
}).then((result)=>{
    return sum(result,5)
}).then((result)=>{
    console.log(result)
}).catch(e=>{
    console.log(e)
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is Async/Await?

A

A tool that makes it easier to work with promises. It provides a syntactical advantage, making code more readible, by avoiding promise chaining, and it keeps all variables within the same scope, which makes it easier to access their values

How well did you know this?
1
Not at all
2
3
4
5
Perfectly