0

Both foo() and addProduct() are methods of same class. addProduct() gets called when a form it's submitted. I was expecting to be displayed first "ok1" and then "ok2" inside Console but it's happening otherwise. I'm doing something wrong?

  async foo(url, obj) {
     const result = await this.http.post(url, obj).toPromise();
     return result;
  }

  addProduct(ProductName, ProductDescription, ProductPrice) {
    const obj = {
      ProductName,
      ProductDescription,
      ProductPrice
    };

    this.foo("http://localhost:4000/products/add", obj).then( (result) => {
        console.log("ok1");
    });
    console.log("ok2");
  }
floreapaun
  • 124
  • 10

3 Answers3

0

console.log("ok2")

is run immediately after sending off the http request. When the http request comes back,

console.log("ok1")

is run

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
0

foo call is asynchronous so it is obvious that calling method will finish its execution irrespective of foo method call. If you need to call ok1 first and then ok2, then you need to call ok2 from inside the result handling part of foo method call.

see below code

async foo(url, obj) {
     const result = await this.http.post(url, obj).toPromise();
     return result;
  }

  addProduct(ProductName, ProductDescription, ProductPrice) {
    const obj = {
      ProductName,
      ProductDescription,
      ProductPrice
    };

    this.foo("http://localhost:4000/products/add", obj).then( (result) => {
        console.log("ok1");
       console.log("ok2"); // this will ensure that ok2 will be always after ok1
    });
  }
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

Make addProduct as async method.

Note You are getting unexpected output because http call happen asynchronously. But the output you getting according to your code is correct. You can learn more about async JavaScript here (MDN)

async foo(url, obj) {
     const result = await this.http.post(url, obj).toPromise();
     return result;
}

async addProduct(ProductName, ProductDescription, ProductPrice) {
    const obj = {
      ProductName,
      ProductDescription,
      ProductPrice
    };

    const result = await this.foo("http://localhost:4000/products/add", obj)
    console.log("ok1");
    console.log("ok2");
}
Priyanshu
  • 39
  • 1
  • 6