简体   繁体   中英

Promise value not getting returned but if I do console.log() it prints the value

Here is my function which returns a promise containing text value of a button

getToggleViewButtonText(){
        return this.toggleBasicOrAdvancedView.getText()
    }

Now, I wrote one more function which takes other functions as a parameter and resolves the promise and returns its value.

promiseResolve(func){
    return func.then(value=>{
         return value
    });

Problem is when I use this

promiseResolve(this.getToggleViewButtonText())

I get promise back instead of text value of button element.But, if I do console.log(value) in promiseResolve function. I can see the value is there. Can some help where I am going wrong here.

Promise.then() returns the promise itself. The point of the promise is that you don't know when it will resolve. So you can only get its results using async methods.

this.getToggleViewButtonText().then(value => {
    // Do something with the value here
});

If the requirement is to get the value of a Promise within code at next line you can use async/await

 function getToggleViewButtonText() { return Promise.resolve(1) } async function promiseResolve(func) { let value = await func; if (value > 1) { return value } else { return value + " is not greater than 1" } } promiseResolve(getToggleViewButtonText()).then(data => console.log(data)) 

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