【问题标题】:Condition check for multiple Async functions多个异步函数的条件检查
【发布时间】:2018-02-09 21:38:09
【问题描述】:

我正在使用带有 Angular 的 Ionic 3。

我有多个异步函数:

async buildNewsItemsViaHttp(){
  let result = await this.http.get()....
}

async buildNewsItemsViaLocalJSON(){
   return await this.http.get()....
}

async getNewsItems(){
   return await this.storage.get()...
}

我想根据异步函数是否返回值来有条件地运行它们。这意味着:

  • 如果 getNewsItems() 会返回数据,则返回它
  • 如果没有,运行 buildNewsItemsViaHttp 看看是否返回数据
  • 如果没有,请运行 buildNewsItemsViaLocalJSON

建议:

async getItems(){
    let result = await.this.getNewsItems();
    if (result) {
        return result;
    } else {
        result = await.this.buildNewsItemsViaHttp();
        if (result) {
            return result;
        } else {            
            result = await.this.buildNewsItemsViaLocalJSON();
            return result;
        }
    }
}

这个解决方案正确吗?

提前致谢

【问题讨论】:

  • 看起来不错,但是当 if 分支返回时,您不需要使用 else。所以你可以通过删除这些来简化一点。

标签: javascript angular asynchronous ionic3


【解决方案1】:

你应该使用某种链接来实现你想要的,下面这个有点幼稚但应该可以工作:

getNewsItems().then((result)=>{
    if (result === "what you need") {
        // do here what you want with the result data
    } else {
         buildNewsItemsViaHttp().then((result)=>{
             if (result === "what you need") {
                  // do here what you want with the result data
             } else {
                 buildNewsItemsViaLocalJSON.then((result)=>{
                 // do here what you need with result
             })
         }
    })
}})

当然你也应该有逻辑来捕捉错误 (.catch(err)=>{})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多