【问题标题】:Returning data from provider promise function in Javascript从 Javascript 中的提供者承诺函数返回数据
【发布时间】:2017-06-15 03:15:27
【问题描述】:

我有一个提供程序,它应该允许我从我需要的 API 返回特定数据。我有这个功能:

public getStoryCount(key: string, val: number) {
    return this.client.getEntries({
        'content_type': xxxxxxxxxxxxxx,
        [key]: val,
    }).then((entries:any) => {
        return entries.total;
    });
}

这是我第一次真正使用 Promise,但我试图在组件中调用它来获取值。我希望能够获得值 entries.total 当我 console.log 得到输出时。

我正在构建一个数据数组以在我的视图中使用,如下所示:

this.homeScreen.push({
  'count': Provider.getStoryCount('sys.id', xxxx)
});

当我 console.log Provider 函数时,我可以看到 promise 中的值,它看起来像这样:

__zone_symbol__state : true
__zone_symbol__value : 13 // this is the value I need to get

如何将数字 13 保存到我的数组 homeScreen['count'] 值中?还是我做错了什么??

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您当前返回的是Promise,而不是实际值。这意味着将您的组件代码修改为:

    Provider.getStoryCount('sys.id', xxxx)
        .then((entries:any) => {
            this.homeScreen.push({
              'count': entries.total
            });
        }
    });
    

    应该可以。

    您还可以让您的 Provider 服务获取值并将其存储为 Observable,以便组件可以订阅该值。

    【讨论】:

      【解决方案2】:

      由于 Promise 是异步的,因此您实际上并没有像您想象的那样返回 entry.total。

      您可能需要提供自己的回调函数,或者简单地返回承诺(由 this.client.getEntries 生成)并将then 添加到结果中。它可能看起来像这样:

      public getStoryCount(key: string, val: number) {
          return this.client.getEntries({
              'content_type': xxxxxxxxxxxxxx,
              [key]: val,
          });
          // The 'then' will be added later
      }
      
      // ...
      
      // Get the promise from the provider, and invoke 'then' here.
      var storyCountPromise = Provider.getStoryCount('sys.id', xxxx);
      storyCountPromise.then((entries:any) => {
          this.homeScreen.push({
            'count': entries.total
          });
      });
      

      【讨论】:

        【解决方案3】:

        这是一个异步操作。你需要在then中传递一个函数:

        Provider.getStoryCount('sys.id', xxxx)
          .then((total) => {
            this.homeScreen.push({
             'count': total
            });
          });
        

        【讨论】:

          【解决方案4】:

          首先,要将 promise 的结果映射到另一个值,请使用 map。

          public getStoryCount(key: string, val: number) {
              return this.client.getEntries({
                  'content_type': xxxxxxxxxxxxxx,
                  [key]: val,
              }).map((entries:any) => {
                  return entries.total;
              });
          }
          

          然后在调用promise返回函数时使用then获取结果

          Provider.getStoryCount('sys.id', xxxx).then((total) => ...use total...);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-08-05
            • 2017-04-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-31
            相关资源
            最近更新 更多