Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using then() in promise

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);
    });
like image 915
Nhan Nguyen Avatar asked Dec 16 '16 07:12

Nhan Nguyen


People also ask

How do you use the promise then?

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() .

Why do we use then in promise?

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.

What is promise resolve () then?

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.

Can we add then after catch in promise?

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.


1 Answers

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.");
  });
like image 72
T.J. Crowder Avatar answered Oct 13 '22 18:10

T.J. Crowder