How to wait for a promise to be resolved?

后端 未结 2 540
陌清茗
陌清茗 2021-02-11 15:15

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. In a perfect wo

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-11 15:52

    In Q if you have a resolved promise you can just take the value with inspect

    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.

提交回复
热议问题