从函数的内部范围返回值

时间:2019-05-10 13:25:03

标签: javascript reactjs typescript

我有一个函数,其中一个“ then”函数嵌套在一个返回值中。我希望将此退货添加到外部退货中。查看代码:

public async getAllWidgets(): Promise <Widget[]> {
  let settings = new SettingsRepository(this.context, null);

  let data: Widget[];

  settings.CountryUrl().then(async(url) => {
    var repositoryUserCountryUrl = new ListRepository(url);
    var cacheKey = "QuickLinksLinksAllWidgets";
    let widgets: any[];

    let multiLingual = await settings.MultiLingual(this.absoluteWebUrl);

    if (multiLingual) {
      let currentLanguage = await Languages.getLanguage(this.context, null, this.absoluteWebUrl);
      cacheKey += "-" + currentLanguage;
      widgets = await repositoryUserCountryUrl.getListItemsByUrlLanguageAware(Constants.QuickLinksListUrl, `local-${cacheKey}`, currentLanguage);
    } else {
      widgets = await repositoryUserCountryUrl.getListItemsByUrl(Constants.QuickLinksListUrl, `local-${cacheKey}`);
    }

    let result: Widget[] = [];
    widgets.map((item) => {
      result.push(this.parseWidget(item));
    });

    let data: Widget[] = result;

    return data; /// HAVE ALL THE DATA I NEED

  });

  return new Promise <Widget[]> (async(resolve) => {
    console.log("data in return" + data)
    resolve(data); /// UNDEFINED DATA
  });
}

当我调用上面的函数时,即使第一个内部返回包含数据,我也什么也没得到,所以我想我必须以某种方式将其添加到外部返回中。我该怎么办?

1 个答案:

答案 0 :(得分:2)

您必须将整个函数包装在新的Promise中,不仅要像您所做的那样在最后,然后解析数据变量。您不能从异步内部返回并期望它不会被未定义,因为该函数可以正常运行并在加载数据之前结束。

所以...

public async getAllWidgets(): Promise<Widget[]>  {
    return new Promise((resolve, error) => {
      // your data calculations...
      resolve(data)
    }
}