0

I have the following code

getNotesContent(){  
        this.svsDb.getNotes(this.order_info.orderid).then(
            data=>{
                console.log("the list of notes content...", data);
                data.history.forEach( (notes:any)=>
                this.noteList.push(
                    {
                        stack:[
                            {text: 'Date: ' + notes.created_date},
                            {text: 'Note/Comments: ' + notes.notes},
                            { text: '--------------------------' },
                        ]
                    }
                )
            )

            }); 

       return this.noteList;    

}

My return value is always empty. Can someone let me know how I can have this function return a value? Thank you for your help.

A

jay4116
  • 57
  • 1
  • 1
  • 9
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – baao Jun 27 '18 at 21:21
  • what does the console.log showing – yer Jun 27 '18 at 21:21
  • 1
    This is because you are returning outside the promise, which means that the promise is not finished when you are returning. You could use async-await pattern, but this depends on which ES subset you are using. Which one is it? You may require an additional package if it is below ES6. – evayly Jun 27 '18 at 21:22
  • yes, I believe I do. "es6-promise-plugin": "^4.2.2", – jay4116 Jun 27 '18 at 22:12

1 Answers1

0

You cannot, a promise will resolve later. When you call your getNotesContent() function, it will return before there are any results. It looks like you are returning the array which will be filled later, so that will have the values you wish. However if the caller needs to wait and handle those results, then you should return a promise and the caller should call then() on it.

getNotesContent(){  
    return this.svsDb.getNotes(this.order_info.orderid)
    .then(data => {
        console.log("the list of notes content...", data);
        data.history.forEach((notes:any) => {
            this.noteList.push(
                {
                    stack:[
                        {text: 'Date: ' + notes.created_date},
                        {text: 'Note/Comments: ' + notes.notes},
                        {text: '--------------------------'},
                    ]
                }
            );
        });
        return this.noteList; // this will now be the promise results
   }); 
}

// sample call
getNotesContent().then(noteList => console.dir(noteList));
Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113