【问题标题】:Why the need to call resolve()?为什么需要调用resolve()?
【发布时间】:2017-11-23 17:23:01
【问题描述】:

我正在查看 A First Reason React app for Javascript developers 上的 Reason 示例

而且我看到他在使用bs-fetch时正在调用Js.Promise.resolve

RepoData.fetchRepos()
  |> Js.Promise.then_(repoData => {
       handleReposLoaded(repoData);
       Js.Promise.resolve();
     })
  |> ignore;

我也在 BuckleScript 代码中看到过类似的代码。比如Bucklescript Cookbook:

Js.Promise.(
  Fetch.fetch "https://api.github.com/users/reasonml-community/repos"
  |> then_ Fetch.Response.text
  |> then_ (fun text -> 
      text 
      |> names
      |> Array.iter Js.log 
      |> resolve)
  |> ignore

在 JS 中,我们通常在创建新的 Promise 时调用 resolve,而不是在使用返回 Promise 的函数时。那么为什么在上述情况下我们需要调用resolve呢?

【问题讨论】:

    标签: promise reason bucklescript


    【解决方案1】:

    Js.Promise.then_ 要求返回一个新的承诺。

    原因是 es6 的 promise 没有正确输入。 then 回调中返回的值是动态包装或(无限)展平的,因此它始终返回一个承诺,而不是嵌套的承诺。这意味着如果我们允许返回任何值 (let then_: ((_ => 'a), Js.Promise.t(_)) => Js.Promise.t('a)),并且如果该值是一个承诺 ('a = Js.Promise.t('b)),它的返回类型将是 Js.Promise.t(Js.Promise.t('b)),但返回的值实际上是被扁平化为Js.Promise.t('b)

    then_ 只接受回调中的一个promise,通过使您返回一个嵌套promise 更加明显,可以稍微缓解这种情况。不过,仍然可以resolve 作出承诺,所以类型仍然不正确,但它会让你更难射中自己的脚。

    在(可能不久的)将来会有一个健全而优雅的 Promise API,但由于设计和实现它是一项艰巨的任务,因此需要一些时间才能做到正确。

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 2018-01-03
      • 2011-08-17
      • 2015-09-28
      相关资源
      最近更新 更多