Function doesn't wait for subscribe to get the information

I am getting the data from firebase saving it in an observable then subscribing to it to extract the data.

In my service i subscribe to an observable to get the data using this method

canAddBookmark(item : bookmark){
     let canAdd = true;
      for(let i =0;i<data.length;i++){
        return canAdd;
      canAdd = true;

    return canAdd;

Which should return a boolean to a function in another class the function:

    let temp:bookmark = {idd:idd,};
    let val =   this.bookmarkDb.canAddBookmark(temp);

    alert("Already book marked");}

the alert with “second” comes before “first”. is there anyway to make the function wait for the other function to return the boolean.

or any better way to get the information from the observable because i am having a lot of issues from it

another example of the issue

in the service:

getItemByIdd(id : number) : items {

    this.items.subscribe( (data)=>{

      for(let i =0;i<data.length;i++ ){


         alert(;/////// the alert shows the right name    (1)
      return this.tempItesm; }
 } } );

    return this.tempItesm;


The class i want to use the function in:


    this.titem= this.dBItems.getItemByIdd(idd);

    /// i want the code here to wait for the function to execute

    alert(; //// the alert shows undefined            (2)


alert (2) comes before (1) is there any possible way to force the code to wait? i tried to do async/await but failed.

Type everything. That includes return values for every function you write. Doing so will help your build tools guide you away from silly bugs. It’s hard to read code when you can’t tell at a glance what a function is saying it’s doing and returning.

Customary naming conventions are also important. It really helps to be able to avoid clashes between types and variables, so always start type names with an uppercase letter.

All that being said, canAddBookmark looks to me like it’s trying to be a time machine. You cannot return a synchronous value from any function that is dependent on an asynchronous input.

Think about it like this. You are a coffee shop. A customer shows up in the middle of the night, asking for a muffin. “Sorry”, you say, “I can sell you a muffin as soon as my shipment arrives from the bakery”. The customer insists that they need the muffin right now. Not going to happen, right?

So, redeclare canAddBookmark to return Observable<boolean>, and rearchitect everybody who calls it to deal with that reality.

1 Like