I need some help regarding Typescript. I was following a tutorial which pulls search data in client side web part. The code for the service is as follows (it works):
const _results:SearchService.ISearchResult[] = [];
return new Promise<SearchService.ISearchResult[]>((resolve,reject) => {
pnp.sp.search({
Querytext: query,
RowLimit: 5,
StartRow:0
}).then((results) => {
results.PrimarySearchResults.forEach((result) => {
_results.push({
title: result.Title,
description: result.HitHighlightedSummary,
link: result.Path,
author: result.Author
});
});
}).then(() => {
resolve(_results);
}).catch((err) => {
reject(new Error(err));
});
});
}
In an attempt to learn and explore more, I came across the await syntax to work with promises which avoids the use of then. I rewrote the above as follows (this also works):
const _results:SearchService.ISearchResult[] = [];
const searchResponse: Promise<SearchService.ISearchResult>[] = [];
const pnpResponse: any = await pnp.sp.search({
Querytext: query,
RowLimit: 5,
StartRow: 0
});
for (let searchResponses of pnpResponse.PrimarySearchResults) {
_results.push({
title: searchResponses.Title,
description: searchResponses.HitHighlightedSummary,
link: searchResponses.Path,
author: searchResponses.Author
});
}
return _results;
Then in my webpart.ts file (render method): I do this (this also works)
const _search: SearchService.ISearchService = new SharePointSearchService.SharePointSearchService();
let resultsHtml: string = "";
let searchResults = await _search.GetSearchResults(query);
for (let result of searchResults) {
resultsHtml += `<div class="ms-ListItem ms-Grid-col ms-u-sm8">
<a href="${result.link}"><span class="ms-ListItem-primaryText" >${result.title}</span></a>
<span class="ms-ListItem-secondaryText">${result.author}<span>
<span class="ms-ListItem-tertiaryText">${result.description}</span>
<span class="ms-ListItem-metaText">10:15a</span>
<div class="ms-ListItem-actions">
<div class="ms-ListItem-action" targerUrl="${result.link}"><i class="ms-Icon ms-Icon--OpenInNewWindow">
</i></div>
</div>
</div>`;
}
My question is: is my understanding of the await correct as how I have it implemented? The function works as expected - however, is it the correct way that I have it implemented or have I missed some critical point in there - perhaps misunderstood how it works (and the function just happens to work although it is implemented incorrectly in principle?)
I thank you all for your input and help. This will really help me learn more.
Thanks.