0

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.

0

await

The await expression causes async function execution to pause, to wait for the Promise's resolution, and to resume the async function execution when the value is resolved. It then returns the resolved value. If the value is not a Promise, it's converted to a resolved Promise.

If the Promise is rejected, the await expression throws the rejected value.

promises

A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

To achieve truly async feature you should go with promises

Learn more about await function

Learn about promises

  • Thanks Venkat. However, from what I have studied so far, await also works with promises. It is just a cosmetic way to code wherein it looks as if you are running a synchronous function - whereas it is all async in the background and it also works with promises. Promises and await are not 2 different patterns - rather await is just a means to avoid those multiple .then() calls. This is what I have managed to learn so far. Please correct me if I am wrong. Thanks – Anil Jul 14 '17 at 18:13
  • Look at the practical example here. stackoverflow.com/questions/43302584/… – Venkat Konjeti Jul 14 '17 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.