title: Return promise from the function
body: <p>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</p>
  
  <pre><code>private InsertPersonInDB(p : Person) {    
       return this.db.find({                              //&lt;- would this return?
                  selector: {objType: 'Person'},
                  fields: ['_id'],
                  sort: ['_id']
              }).then( result =&gt; {                         
                  let allpersondIds : string[] = [];
                  (result.docs).forEach(rec =&gt; {
                      allpersondIds.push(rec._id);
                  });
                  return allpersondIds;                
              }).then ( allpersonIdsInDB =&gt; {                
                  var id = this.getIdfromPersonName(person.personName, allpersonIdsInDB);
                  person._id = id;
                  return this.db.post(person)            //&lt;- or would this return?
              }
  }
  
  //Calling function
  for(let person of this.persons) {
      InsertPersonInDB(person).then(result =&gt; {
          console.log(result)
          //Some UI updates       
      }).catch(err =&gt; {
          console.log(err)
          //Some UI updates notifying user about failure  
      }); 
  }
  </code></pre>
  
  <p>Here, I have two return, first is</p>
  
  <blockquote>
    <p>return this.db.find</p>
  </blockquote>
  
  <p>which <em>find</em> function is a promise</p>
  
  <p>and end of the then chain returns </p>
  
  <blockquote>
    <p>return this.db.post(person)</p>
  </blockquote>
  
  <p>even <em>post</em> function is a promise.</p>
  
  <p>Here, I have three questions</p>
  
  <p>1) When this function executes, what would return? </p>
  
  <p>2) If the function immediately returns the promise, when would the chain <em>thens</em> execute? </p>
  
  <p>2) What are better approaches to refactored the promise chain in a layered application. E.g. Few chain <em>then</em> needs to be executed in the service, other needs to be executed in UI, how do I structure my promises code?</p>