简体   繁体   English

如果不是承诺,如何等待值返回

[英]how to wait a value to return if it is not a promise

for example, there is an asynchronous function that i don't develop myself, but I know for a random time(in a few seconds) that function will return a value. 例如,有一个我自己没有开发的异步函数,但是我知道在随机时间内(几秒钟内)该函数将返回一个值。 Is that any way to wait for the return if it doesn't return a promise? 如果不返回承诺,有什么办法等待回报?

Not as such. 不是这样的。

You could write a wrapper function that returns a promise which polls until it gets a result. 您可以编写一个包装函数,该函数返回一个承诺,该承诺将轮询直到获得结果。

The promise would then call the function you didn't write repeatedly (eg with setInterval ) until it returned a value and then pass it to resolve. 然后,promise会调用您没有重复编写的函数(例如,使用setInterval ),直到它返回一个值,然后将其传递给解析。

function wrap_function () {
    return new Promise(function (resolve, reject) {
         var interval = setInterval(function () {
             var result = the_origional_function();
             if (result) {
                 clearInterval(interval);
                 resolve(result);
             }
         }, 2000);
    });
}

(Assuming I'm interpreting the statement "in a few seconds) that function will return a value" correctly) (假设我在“几秒钟之内就解释了该语句将正确返回一个值”的语句)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM