简体   繁体   English

承诺值未返回,但如果我执行console.log(),它将输出值

[英]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 这是我的函数,它返回一个包含按钮文本值的promise

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. 现在,我编写了另一个函数,该函数将其他函数作为参数并解析了promise并返回其值。

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. 我得到的是Promise而不是按钮元素的文本值。但是,如果我在promiseResolve函数中执行console.log(value)。 I can see the value is there. 我可以看到值在那里。 Can some help where I am going wrong here. 能为我在这里出问题的地方提供一些帮助。

Promise.then() returns the promise itself. Promise.then()返回承诺本身。 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 如果要求在下一行获取代码中的Promise值,则可以使用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)) 

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

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