【问题标题】:new Promise failing to wrap callback新的 Promise 未能包装回调
【发布时间】:2017-01-30 18:11:29
【问题描述】:

这是使用回调的工作代码(咖啡脚本中的 this)

requestUtils.post = (path, data) ->
  requestUtils.request.post(
    "#{requestUtils.apiHostname}#{path}",
    { json: data },
    logFn
  )

当我运行它时,我看到记录了 HTTP 响应。我想将logFn 回调转换为resolve

这是我的尝试:

requestUtils.post = (path, data) ->
  new Promise (resolve, reject) ->
    requestUtils.request.post(
      "#{requestUtils.apiHostname}#{path}",
      { json: data },
      resolve
    )

看起来很简单。当我调用该函数并像这样传递一个承诺处理程序时:

  GM.requestUtils.post("/getVehicleInfoService", {id: "#{id}"})
  .then () ->
    console.dir arguments

当我运行它时,我没有看到任何打印内容。 then 处理程序似乎没有被调用。我不确定为什么。我以为我掌握了承诺,但显然没有

【问题讨论】:

  • 你不会像.then(args => console.dir(args))一样将任何返回的参数传递给then的回调

标签: javascript coffeescript promise


【解决方案1】:

想通了,我想我必须将resolve 包装在另一个函数中,如下所示:

requestUtils.post = (path, data) ->
  new Promise (resolve, reject) ->
    requestUtils.request.post(
      "#{requestUtils.apiHostname}#{path}",
      { json: data },
      () -> resolve arguments
    )

不同之处在于我传递的回调不仅仅是传递resolve

() -> resolve arguments

不完全确定为什么会这样,因为它似乎在做与自己传递 resolve 完全相同的事情。

如果有人能解释一下,我会很感兴趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多