简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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