I'm working on a project that uses a library called contentRecordHelper. When I run a record object through contentRecordHelper.addTitleFilter(), it populates the record with a bunch of different properties based on what kind of record it was.
Record before:
{
"_title": "Test Record",
"_type": "content",
"_id": "029828ABF"
}
Record after it's run through contentRecordHelper.addTitleFilter():
{
"_title": "Test Record",
"_type": "content",
"_id": "029828ABF",
"server_id": "VAL8378",
"client_id": "SIRIUS",
"$titleFilter":"General",
"$contentFilter": "Standard:ContentRecord",
"$contentType":"",
"$systemType":""
}
As you can see from above, there are two attributes added at the end which are empty: $contentType and $systemType. That's because those two are populated by an asynchronous function which is started within contentRecordHelper.addTitleFilter(), and which gets added approximately 1000ms later.
However, as soon as this data is generated, it is passed into a grid. And that grid must be refreshed if the information is updated, so that it can display properly. Fortunately there is a grid.refreshGrid() function to do so. I have been calling it with a timeout, so my code looks like this:
function addRecordToGrid(record: any): void {
this.contentRecordHelper.addTitleFilter(record);
this.grid.rowData.push(record);
setTimeout(() => {
this.grid.refreshGrid();
}, 1000);
}
Now strictly speaking this works fine, but one of my senior devs pointed out to me that we should not rely on a hard 1000 ms, because that won't always be reliable in the case of a slow back-end connection. He said that instead, I should use a promise, so that as soon as record.$systemType && record.$contentType exist, I call grid.refreshGrid(). And he's right - that makes perfect sense. The only trouble is, I've never written a promise before, and just about every example I can find calls some asynchronous function, and waits for it to complete. In my case, contentRecordHelper.addTitleFilter() completes almost instantly, even though certain parts of the result don't come through until later.
How can I write a promise that, simple as heck, just waits for a condition to be true, such as (record.$systemType && record.$contentType) ? If it's not possible, then what is the best way for me to use a promise to solve my issue? Is it possible to do this without making changes to contentRecordHelper.addTitleFilter()? The mechanisms behind that function are very complicated and if I can possibly avoid making changes to it that would save me a lot of stress.
I'm pretty new to the project I'm working on (and typescript in general), so I apologize if this is obvious.