Promises
Promises
A JavaScript Promise is created with the newPromise constructor function-new Promise()
. A promise will let you start some work that will be doneasynchronouslyand let you get back to your regular work. When you create the promise, you must give it the code that will be run asynchronously. You provide this code as the argument of the constructor function:
new Promise(function () {
window.setTimeout(function createSundae(flavor = 'chocolate') {
const sundae = {};
// request ice cream
// get cone
// warm up ice cream scoop
// scoop generous portion into cone!
}, Math.random() * 2000);
});
This code creates a promise that will start in a few seconds after I make the request. Then there are a number of steps that need to be made in thecreateSundae
function.
Indicated a Successful Request or a Failed Request
But once that's all done, how does JavaScript notify us that it's finished and ready for us to pick back up? It does that by passing two functions into our initial function. Typically we call theseresolve
andreject
.
The function gets passed to the function we provide the Promise constructor - typically the word "resolve" is used to indicate that this function should be called when the request completes successfully. Notice theresolve
on the first line:
new Promise(function (resolve, reject) {
window.setTimeout(function createSundae(flavor = 'chocolate') {
const sundae = {};
// request ice cream
// get cone
// warm up ice cream scoop
// scoop generous portion into cone!
resolve(sundae);
}, Math.random() * 2000);
});
Now when the sundae has been successfully created, it calls theresolve
method and passes it the data we want to return - in this case the data that's being returned is the completed sundae. So theresolve
method is used to indicate that the request is complete and that it completed successfully.
이제 sundae가 성공적으로 만들어지면 resolve 메서드를 호출하고 반환할 데이터를 전달합니다. 이 경우 반환되는 데이터는 완료된 sundae입니다. 따라서 resolve 메소드는 요청이 완료되었고 성공적으로 완료되었음을 나타내기위해 사용됩니다.
요청에 문제가있어 완료 할 수 없는 경우 함수에 전달된 두 번째 함수를 사용할 수 있습니다. 일반적으로 이 함수는 "reject"라는 식별자에 저장되어 어떤 이유로든 요청이 실패 할 경우 이 함수를 사용해야합니다. 첫 번째 줄에서 reject를 확인하십시오.
If there is a problem with the request and it couldn't be completed, then we could use the second function that's passed to the function. Typically, this function is stored in an identifier called "reject" to indicate that this function should be used if the request fails for some reason. Check out thereject
on the first line:
new Promise(function (resolve, reject) {
window.setTimeout(function createSundae(flavor = 'chocolate') {
const sundae = {};
// request ice cream
// get cone
// warm up ice cream scoop
// scoop generous portion into cone!
if ( /* iceCreamConeIsEmpty(flavor) */ ) {
reject(`Sorry, we're out of that flavor :-(`);
}
resolve(sundae);
}, Math.random() * 2000);
});
So thereject
method is used when the requestcould not be completed. Notice that even though the request fails, we can still return data - in this case we're just returning text that says we don't have the desired ice cream flavor.
A Promise constructor takes a function that will run and then, after some amount of time, will either complete successfully (using theresolve
method) or unsuccessfully (using thereject
method). When the outcome has been finalized (the request has either completed successfully or unsuccessfully), the promise is now_fulfilled_and will notify us so we can decide what to do with the response.
Promises Return Immediately
The first thing to understand is that a Promise will immediately return an object.
const myPromiseObj = new Promise(function (resolve, reject) {
// sundae creation code
});
That object has a.then()
method on it that we can use to have it notify us if the request we made in the promise was either successful or failed. The.then()
method takes two functions:
- the function to run if the request completed successfully
- the function to run if the request failed to complete
mySundae.then(function(sundae) {
console.log(`Time to eat my delicious ${sundae}`);
}, function(msg) {
console.log(msg);
self.goCry(); // not a real method
});
As you can see, the first function that's passed to.then()
will be called and passed the data that the Promise'sresolve
function used. In this case, the function would receive thesundae
object. The second function will be called and passed the data that the Promise'sreject
function was called with. In this case, the function receives the error message "Sorry, we're out of that flavor :-(" that thereject
function was called with in the Promise code above.