Search code examples
angulartypescriptpromisees6-promise

How to make promise in Typescript/Angular 2?


I have 5 functions, i want them to execute recordingly after one of them finished, i dont know how to implement promises, if someone can help

function1(){
    .......
    }
function2(){
    .......
    }
function3(){
    .......
    }
function4(){

    function3();
    }
function5(){

function1();
function2();
function4();

Function5 executes function1, but function2 should wait until function1 finishes, and function4 should wait unitl function1 and function2 finish.


Solution

  • I attached an example that uses promises and chains them. I'm not 100% if what you're asking is what you really want, so i tried to show different ways of chaining. f5 waits for f1 and f2 to finish in parallel while f3 waits for f1 to finish before waiting for f2 to finish.

    http://www.webpackbin.com/N1_9QCcDG

    Look in the app.component.ts file.

    It is worth mentioning that each call to a function will return a NEW promise, which is why f3 finishes after f5. If you kept a reference to each initialized promise, then f3 and f5 would finish at the same time because f1 and f2 would run in parallel, even though f3 wouldn't check to see if f2 was done until f1 was done - and since f2 would finish a second before f1, by the time f3 checking when f2 would be done - it would already be done :)

    Basically in Angular2 you create promises the ES6 way like this:

    new Promise(function (resolve, reject) { ... });
    

    In typescript that can be simplified like this:

    new Promise((resolve, reject) => { ... });