I'm using promise in the block of code below, 2 first then() I dont return any value, so i wonder that is the function in the first then() called before the function in the next then(). Im using typescript in angular 2. Thank you :D
Promise.resolve()
.then(()=>{
this.getListStatus();
})
.then(()=>{
return this._laundryServiceOrderService.findAll(true, offset, this.itemsPerPage, filterQuery)
})
.then((response) => {
this.orders = response.data;
this.totalItems = response.totalItems;
})
.catch(error => {
FlashMessage.setError(error.message);
});
A promise always starts out in the pending state. If the promise transitions to the fulfilled state, JavaScript calls the onFulfilled() function. If you call then() on a promise that is already fulfilled, JavaScript will immediately call onFulfilled() .
The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call. Previously, callback functions were used instead of this function which made the code difficult to maintain.
The Promise.resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
The catch method is used for error handling in promise composition. Since it returns a Promise , it can be chained in the same way as its sister method, then() . catch() internally calls then() . This is observable if you wrap the methods.
first then() I dont return any value, so i wonder that is the function in the first then() called before the function in the next then().
Yes, it is. (This can trivially be checked with a debugger.)
It doesn't matter that it doesn't return a value; that's effectively the same as doing return undefined
. So the next callback in the chain will see undefined
as the resolution value, but since that next callback doesn't care about the resolution value, that's fine.
Here's a simple example demonstrating it:
Promise.resolve("a")
.then(result => {
console.log("First callback got: " + result); // Gets "a"
})
.then(result => {
console.log("Second callback got: " + result); // Gets undefined
return "b";
})
.then(result => {
console.log("Third callback got: " + result); // Gets "b"
})
.catch(error => {
console.log("There's no error above, this won't get triggered.");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With