当我刷新多个数据源时,我正在使用Iced coffescript和upshot js。刷新方法有两个回调一个用于成功,一个用于错误,我想等待每个调用进行回调。
我无法看到如何在没有附加功能的情况下使用ided coffescript执行此操作。我的问题是 - 是否有一种更优雅的方式可以推迟到多个回调之一?
这是我目前的代码:
refreshMe = (key, value, result) =>
value.refresh(
(success)=>
result success
,
(fail, reason, error)=>
result undefined, fail
)
@refresh = () =>
success={}
fail={}
await
for key, value of @dataSources
refreshMe key, value, defer success[key], fail[key]
答案 0 :(得分:5)
这是我发现的唯一方法。我在Backbone中使用它并使用@icedSave包装(例如)模型的@save函数:
# An IcedCoffeescript friendly version of save
icedSave: (callback) ->
@save {},
success: (model, response) -> callback(true, model, response)
error: (model, response) -> callback(false, model, response)
答案 1 :(得分:1)
以下是我用于将Promises .then (-> onSuccess), (-> onError)
转换为errbacks (err, result) ->
的一些代码:
# You can write like this:
await value.refresh esc defer e, result
# onError - function to be called when promise rejected.
# onSuccess - function to be called when promise is fulfilled.
module.exports = esc = (onError, onSuccess) ->
util = require 'util'
return (result) ->
if util.isError result
# Always send back an error to first handler.
onError? result
else if onSuccess?
console.log onSuccess, result
# `await fn esc done, defer result`
onSuccess? result
else
# `await fn esc done`
onError? null, result
您可以稍微修改esc
函数来处理每个回调的多个参数。
答案 2 :(得分:0)
iced.Rendezvous lib是针对这种情况明确做出的:在多个回调的第一个返回。来自the docs:
这是一个展示不同输入和输出的例子 约会。它执行两次并行DNS查找,并仅在何时报告 第一个回归:
hosts = [ "okcupid.com", "google.com" ]; ips = errs = [] rv = new iced.Rendezvous for h,i in hosts dns.resolve hosts[i], rv.id(i).defer errs[i], ips[i] await rv.wait defer which console.log "#{hosts[which]} -> #{ips[which]}"