Return promise from the function

44,431

Solution 1

First of all, I think you can easily test our your questions by just making some small examples for yourself. When I am unclear about how things work, I find it very useful to create a small example to just try out and see what happens. Lets do that for this question as well (see also https://plnkr.co/edit/K18o4Lp2jtUincjyG5wi?p=preview for the working version; open the console to see the results!):

function test() {
  return returnPromise().then((value) => {
    console.log('1st then, inside test(): ' + value);
    return 'Hello';
  }).then((value) => {
    console.log('2nd then, inside test(): ' + value);
    return 'world';
  });
}

function returnPromise() {
  return new Promise(function(resolve, reject) {
    resolve('start of new Promise');
  });
}

test().then((value) => {
  console.log('3rd then, after calling test: ' + value);
});

For your questions:

  1. You return the Promise together with all the chained then functions. If you add another then to the returned Promise, it will be added at the end of the chain. That is what you see when we are doing test().then(...).
  2. A Promise tells you that it will execute at some point in time, without telling you when. The then chain will execute whenever the Promise resolves. You can see that in more detail in returnPromise. Here we return a new Promise. The body of the Promise calls the resolve method when it is done (in this case that is instantly), triggering the Promise to resolve and execute all then methods chained to the Promise. Usually the Promise won't resolve instantly, but will perform an async task (e.g. retrieving data from a server) first.
  3. That really depends on the type of application and what you are looking for. Your current approach is not bad in itself, as long as the responsibilities are clearly defined.

Solution 2

1) A promise that resolves to the result of the db.post(person) request.

2) The callback passed to then(...) is executed when the db.post() call returns a response or throws an exception.

3) No idea. I don't think there is a general answer. It depends on what API you want to provide to the users of this service.

Share:
44,431
Shabbir
Author by

Shabbir

Updated on July 09, 2022

Comments

  • Shabbir
    Shabbir almost 2 years

    I have a shallow understanding of JavaScript Promise and promise chain. Say, I have a method as shown below. It's written is TypeScript, but could be modified to match JavaScript ES6

    private InsertPersonInDB(p : Person) {    
         return this.db.find({                              //<- would this return?
                    selector: {objType: 'Person'},
                    fields: ['_id'],
                    sort: ['_id']
                }).then( result => {                         
                    let allpersondIds : string[] = [];
                    (result.docs).forEach(rec => {
                        allpersondIds.push(rec._id);
                    });
                    return allpersondIds;                
                }).then ( allpersonIdsInDB => {                
                    var id = this.getIdfromPersonName(person.personName, allpersonIdsInDB);
                    person._id = id;
                    return this.db.post(person)            //<- or would this return?
                }
    }
    
    //Calling function
    for(let person of this.persons) {
        InsertPersonInDB(person).then(result => {
            console.log(result)
            //Some UI updates       
        }).catch(err => {
            console.log(err)
            //Some UI updates notifying user about failure  
        }); 
    }
    

    Here, I have two return, first is

    return this.db.find

    which find function is a promise

    and end of the then chain returns

    return this.db.post(person)

    even post function is a promise.

    Here, I have three questions

    1) When this function executes, what would return?

    2) If the function immediately returns the promise, when would the chain thens execute?

    2) What are better approaches to refactored the promise chain in a layered application. E.g. Few chain then needs to be executed in the service, other needs to be executed in UI, how do I structure my promises code?

  • Sjoerd
    Sjoerd over 7 years
    I am not sure if I understand your argument correctly. I believe the executor is the function(resolve, reject) part. That has no return statement in there; it only calls the resolve method.
  • Sjoerd
    Sjoerd over 7 years
    Could you give a working Plunker example, because I am still not sure what you mean. If you want to chain thens, you return new Promises from within your then. The MDN text explains that you can either construct a new Promise that resolves, or just return any value (which will then be automatically wrapped in a Promise and resolved for you). Leaving the return statements out would also not allow you to pass along information from then to then.
  • ArneHugo
    ArneHugo over 7 years
    Wow, i did not know that you can "return any value (which will then be automatically wrapped in a Promise and resolved for you)". You are absolutely right. I'll delete my confused comments.