I was migrating some code from Angular to VueJS. This is code to retrieve some data from a server and process it.

The Angular code using Observables, and you can use pipes to run different actions to process the data before it is returned to the calling data. In this case, the Angular code was converting the generic JSON data to custom objects before returning them.

How do I perform the same process with regular JS Promises? It turned out it wasn't that hard, you can daisy chain 'then' statements to process the results. Look at this:

view plain print about
1function myFunctionToReturnCustomObject(): Promise<CustomObject> {
2 return new Promise((resolve)=>
{
3 resolve({
4 id: 1,
5 data: "value",
6 });
7 }).then((result) => {
8 return Object.assign(new MyCustomObject(), result);
9 })
10 }

This code creates a new promise and immediately returns a value. The function also contains a 'then()' statement to process the results. That is the first then().

The second then() would be on the calling code:

view plain print about
1myFunctionToReturnCustomObject().then(() => {
2 console.log(result);
3});

All works, and you can daisy chain then() statements to your hearts content.

Play with a JFiddle here.