【问题标题】:How to call chain of promise functions?如何调用承诺函数链?
【发布时间】:2018-07-06 01:20:34
【问题描述】:

我需要调用一个承诺链:

main(): Promise<any> {
  1) call get();
  2) then `get()` is finished call getTwo()
  3) When `getTwo()` is finished return promise to main() function
}

get(): Promise<any>  {
  //
}

getTwo(): Promise<any>  {
  //
}

我试图证明我需要做什么。

【问题讨论】:

标签: angular promise angular-promise


【解决方案1】:

这就是承诺链的运行方式:

return this.get()
.then(data1 => {
    return this.getTwo(data1);
}).then(data2 => {
    return data2;
})

更多详情,do read

这个更短的版本可能是 @JoeClay 的 cmets

this.get().then(this.getTwo)

【讨论】:

  • 请注意,您可以通过使用隐含返回来使这个稍微简洁一些:this.get().then(data1 =&gt; this.getTwo(data1))
  • 其实你可以走得更远:this.get().then(this.getTwo)
  • 如何传递变量finsh并在链循环结束时将其作为真值返回?
  • @Jessie,只需将 return 放在 this.get 之前就完成了
【解决方案2】:

你似乎在寻找

main(): Promise<any> {
  return get().then(getTwo);
}

请注意,当 getTwo 完成时,它不会“将承诺返回给 main() 函数”,而是解析 then 创建并立即返回的承诺。

【讨论】:

  • 你能扩展这个例子吗?
  • 为了什么?它正是问题所要求的。
猜你喜欢
  • 2017-08-12
  • 1970-01-01
  • 2017-03-26
  • 2022-01-08
  • 2017-03-31
  • 1970-01-01
  • 2016-08-06
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多