[英]How to wait for a promise to be resolved?
I'm dealing with a NodeJs framework that requires a certain function to be synchronous, but I need to retrieve a value that can only be accessed asynchronously. 我正在处理需要某个函数同步的NodeJs框架,但我需要检索一个只能异步访问的值。 In a perfect world, I would be able to return a promise, but I can't. 在一个完美的世界里,我能够回报一个承诺,但我不能。
As a quick-and-dirty solution, I created the following method: 作为一个快速而肮脏的解决方案,我创建了以下方法:
exports.synchronizePromise = function(promise) {
var value;
promise.then(function(promiseValue) {
value = promiseValue;
});
while (!value) {} // Wait for promise to resolve
console.log("DONE: " + value); // Never reached
return value;
};
But I get an error. 但是我收到了一个错误。 Is there any way to accomplish what I need? 有没有办法完成我需要的东西?
Given that node is by default only single threaded there isn't really an easy way to solve this. 鉴于该节点默认只有单线程,因此实际上没有一种简单的方法可以解决这个问题。 There is one though. 虽然有一个。 Bases on generators/fibers you can add a sort of concurrent execution to node. 基于生成器/光纤,您可以向节点添加一种并发执行。 There is a waitfor
implementation based on that. 有一个基于此的waitfor
实现 。
In Q if you have a resolved promise you can just take the value with inspect 在Q中,如果您有一个已解决的承诺,您可以通过检查获取该值
exports.synchronizePromise = function(promise) {
var i = promise.inspect();
if (i.state === "rejected") {
throw i.reason;
} else if (i.state === "fulfilled") {
return i.value;
} else {
throw new Error("attempt to synchronize pending promise")
}
};
However if the promise is pending, it is truly asynchronous and your question doesn't then make sense and the function will throw an error. 但是,如果promise是挂起的,那么它确实是异步的,那么你的问题就没有意义了,函数会抛出一个错误。
Promises are asynchronous. Promise是异步的。 They represent a future value--a value available in 1ms, or 1 minute, or 1 day, or 1 year in the future, or never. 它们代表未来价值 - 未来1毫秒,1分钟,1天或1年可用的价值,或永远不会。 By definition, there is no way to "force" them to resolve, other than a time machine. 根据定义,除了时间机器之外,没有办法“强迫”它们解决。
If you have upstream logic which is built on the premise of synchronicity, but for whatever reason things it was depending on are now asynchronous, you have to refactor that upstream component to operate asynchronously as well. 如果您的上游逻辑建立在同步性的前提下,但无论出于何种原因它依赖的东西现在都是异步的,您必须重构该上游组件以便异步操作。 There is no other alternative. 没有其他选择。
If your framework "requires a certain function to be synchronous" when that function is not or cannot be synchronous, then the framework is poorly designed and unusable, or at least not usable for your problem. 如果您的框架“需要某个函数是同步的”,当该函数不能或不能同步时,那么框架设计很差且无法使用,或者至少不能用于您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.