I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6.
private InsertPersonInDB(p : Person) {
return this.db.find({ //<- What does 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 does this return something else?
}
}
//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
});
}
In this piece of code, there are two returns. First is
return this.db.find
which involves a promise from the find function.
And towards the end of the last then block, we have
return this.db.post(person)
This too deals with a promise in the form of the post function.
I have three questions:
1) When this method is executed, what exactly gets returned?
2) If the method instantly returns a promise, when do the subsequent thens get executed?
3) How should one go about restructuring a promise chain in a multi-layered application? For instance, some then blocks need to run in the service layer while others in the UI. What would be an effective approach to organizing promise-related code like this?