Async / Await не работает должным образом с функцией карты ionic 4, машинопись - PullRequest
0 голосов
/ 20 июня 2019

Как я уже упоминал в заголовке, у меня есть метод, который содержит функцию карты.

Я использую ионный 4.

 async searchedData(data){
      if(this.searchedItems.length == 0){
        this.clearfilter()
      }
      if(data == "cleardata"){
        this.searchedItems = [];
      }
       else{
       //after searching
       console.log(data)     
      await data.map(async x=>{
        x["file_type"] =x.resource_name.substring(x.resource_name.lastIndexOf('.')+1)
        user.forEach(element => {
          if(x["user_id"] == element.id){
                return x["userobj"] = element;
              }
          });
        x["socialIcons"] = this.socialIcons;
        x["user_reaction"] = await this.getCreativeReactions(x)
        console.log(x["user_reaction"]) 
        return x;
      }),

        this.searchedItems = this.searchedItems.concat(data);
      }
    }

Проблема с этой строкой:

x["user_reaction"] = await this.getCreativeReactions(x) 
 console.log(x["user_reaction"]) 

getCreativeReactions Код показан ниже

getCreativeReactions(x:any){
     this.creativeServices.getCreativeReactions1(x["id"],x["userobj"]["id"]).pipe(map(res1=>res1.json())).subscribe(res1=>{
          x["user_reaction"] = res1;
          x["user_reaction"].forEach(element=>{
            switch(element["latestReaction"]){
             case 'like' :{
              x["socialIcons"][0]["color"] = "danger" 
              x["socialIcons"][0]["operation"] = "cancellike"
              break;
             } 
             case "unlike":{
              x["socialIcons"][1]["color"] = "danger" 
              x["socialIcons"][1]["operation"] = "cancelunlike"
              break;  
             }
             case "cancellike":{
             x["socialIcons"][0]["color"] = "default" 
             x["socialIcons"][0]["operation"] = "like"
              break;
             }
             case "cancelunlike":{
             x["socialIcons"][1]["color"] = "default" 
             x["socialIcons"][1]["operation"] = "unlike"
              break;
             }
            }
          })
          return x["user_reaction"]
        })

      }

У меня есть метод getCreative реакции, который возвращает массив объектов.Но проблема в том, что хотя await имеет префикс, как показано выше, сначала выполняется console.log (), а затем вызывается метод. Поэтому я получаю x ["user_reaction"] как неопределенное.

Я ошибаюсь с помощью асинхронного / ожидающего синтаксиса с функцией отображения ??

1 Ответ

1 голос
/ 20 июня 2019

заставить ваш getCreativeReactions метод вернуть Обещание с разрешением

Как это

getCreativeReactions(x: any) {
    return new Promise((resolve, reject) => {
        this.creativeServices.getCreativeReactions1(x["id"], x["userobj"]["id"]).pipe(map(res1 => res1.json())).subscribe(res1 => {
            x["user_reaction"] = res1;
            x["user_reaction"].forEach(element => {
                switch (element["latestReaction"]) {
                    case 'like': {
                        x["socialIcons"][0]["color"] = "danger"
                        x["socialIcons"][0]["operation"] = "cancellike"
                        break;
                    }
                    case "unlike": {
                        x["socialIcons"][1]["color"] = "danger"
                        x["socialIcons"][1]["operation"] = "cancelunlike"
                        break;
                    }
                    case "cancellike": {
                        x["socialIcons"][0]["color"] = "default"
                        x["socialIcons"][0]["operation"] = "like"
                        break;
                    }
                    case "cancelunlike": {
                        x["socialIcons"][1]["color"] = "default"
                        x["socialIcons"][1]["operation"] = "unlike"
                        break;
                    }
                }
            })
            resolve(x["user_reaction"]); // here we return the awaited value
        })
    });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...