Refreshing JavaScript – Calling an Async method within Map method in Typescript – SPFx

Sathish Nadarajan
 
Solution Architect
August 27, 2021
 
Rate this article
 
Views
1164

Recently faced an issue. I need to iterate a list of items and need to call an Async method. But the map needs to wait until the last async method is been returned. Usually what happens is, since the method is async, after the first value, it goes beyond the map method and returns. For that, we must write the method with async and Promise All. The pseudo method is as below.

public getTasks = async (Id: number): Promise<any> => {
    try {
      let tasksListItems = await sp.web.lists.getByTitle('Tasks').items.expand('AssignedTo').select('*', 'AssignedTo/Title', 'AssignedTo/EMail', 'AssignedTo/Name').filter(`ProjectID eq ${Id} `).get();

      let taskIds = [];
      taskIds = await Promise.all(tasksListItems.map(async item => {
        return {
          key: item.Id,
          text: item.AssignedTo1.Title,
          taskTitle: item.Title,
          isMember: await graphDataProvider.isMemberOfOffice365Group(item.AssignedTo.Name.split('|')[2], await this.getCurrentUserPrinciple())
        }
      }));
      return taskIds.filter(task => task.isMember);
    }
   catch (error) {
      return null;
    }
  }

Points to be considered.
1. The method should be declared as async method.
2. The map should be surrounded with await Promise.all()
3. Within the map method, we can very well call the async method using the await keyword.

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment