TypeScript High Performance by Kher Ajinkya

TypeScript High Performance by Kher Ajinkya

Author:Kher, Ajinkya [Kher, Ajinkya]
Language: eng
Format: azw3
Publisher: Packt Publishing
Published: 2017-08-24T04:00:00+00:00


// public methods

public getFeed(feedCategory: FeedCategory): Promise<IUserFeed[]>

{

console.log(FeedCategory[feedCategory] + ' fetch begins',

Date.now() - baseStartTime);

return new Promise<IUserFeed[]>((resolve, reject) => {

// simulating an asynchronous network request

setTimeout(() => {

let resultFeed: IUserFeed[] = [];

this.fakeUserFeed.forEach((userFeed: IUserFeed) => {

if (userFeed.feedCategory === feedCategory) {

resultFeed.push(userFeed);

}

});

if (resultFeed.length === 0) {

reject(new Error("No feed found for the " +

FeedCategory [feedCategory] + " category"));

} else {

resolve(resultFeed);

}

}, 5000);

});

}

}

In the preceding code snippet, we declare the FeedCategory enum and IUserFeed interface as before. The FeedQuery class has the same fakeUserFeed private variable too.

The public method getFeed is where things change. First off, this method has a different signature than before. The earlier method took in two parameters, FeedCategory and ICallback and returned void. This method takes in only one parameter, FeedCategory and returns a promise of type IUserFeed[].

Similar to before, the asynchronous setTimeout function is used to mimic a network request. After the set time has elapsed, fakeUserFeed is searched for all feeds belonging to the passed in category. Previously, we called the supplied callback with either the result feed or an error, based on whether any feed for the passed in category was found. Now, we call the two Promise methods we looked at earlier, resolve and reject, with the result feed and error respectively.

Now, you would also need to update your application using this class. Earlier, you would write your own callback with custom logic, and supply this to the preceding getFeed method. In this case, you needn't pass any callback. However, you would need to handle the promise returned by the getFeed method. Let us look at the following code snippet that handles the returned promise using the then…catch technique:

const baseStartTime: number = Date.now();



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.