【发布时间】:2020-05-04 16:35:50
【问题描述】:
我有一个纯同步的验证库,但通常用作异步函数链的一部分。但是,我必须维护现有的同步 API,并希望将 promise API 设为可选。
我能否以某种方式(在运行时)检测函数是否是 Promise 链的一部分?
这很容易使用回调,因为您可以检查是否传入了回调。我知道我可以传入一个可选的 Promise 布尔值,但这似乎不优雅。
我还考虑过做一个回调接口并使用一个库将回调接口动态转换为基于 Promise 的接口。但是,我在 Haxe 工作,我希望将转换/抽象保持在最低限度。
我也明白,您可以将常规函数夹在 promise 之间,但在某些情况下,两者的行为会有所不同。
最终编辑对于为什么我不能只返回相同的值有很多困惑,第一个示例(如下)似乎没有帮助。请记住,这仍然是简化的。
//mix of sync with promise
new Promise(function(resolve, reject){
var safeToAdd = thingTracker.preflight(newThing);
if(safeToAdd){
return client.request.addThing(newThing); //send request to server
} else {
reject(newThing.errorMessages); //requires explicit reject, cannot just pass results along
}
}).then(function(newThing){ //client and server both cool with newThing?
thingTracker.save(newThing);
}).catch(function(errorMessages){ //handles errorMessages from client and server
ui.show(errorMessages);
});
//pure promise
thingTracker.preflight(newThing).then(function(){
return client.request.addThing(newThing); //sends request to server
}).then(function(newThing){ //client and server both cool with newThing?
thingTracker.save(newThing);
}).catch(function(errorMessages){ //handles errorMessages from client and server
ui.show(errorMessages);
});
(旧)编辑澄清(但不是真的):
function preflight(thing){
var validity = thing === 42;
if(promise){
if(validity){
return Promise.resolve(validity);
} else {
return Promise.reject(validity);
}
} else {
return validity;
}
}
显然我可以在then 的匿名函数中进行相同的检查,但这并不比直接使用同步接口好多少。另请注意,这是一个非常简单的示例,在实际函数中,thing 会产生副作用并产生消息。
编辑为了更好地说明我的观点,这里是gist 的样子。
【问题讨论】:
-
你是在问如何检测一个函数是否返回一个promise,或者如何决定你的函数是否应该返回一个promise?
-
如果我的函数应该返回一个承诺。
-
"一个纯同步的验证库" - 然后让它保持同步。没有理由在你身边使用承诺(相反,有理由不使用承诺)。不管调用来自哪里,同步函数也很容易集成到异步链中。
标签: javascript promise