Search code examples
javascriptasynchronouspromise

javascript Get value instead of promise


I would like get a value from a promise but dont know how.

I tried this way:

function connected(p) {

var url = getURL();

async function getURL() {
    var test = "";
    let tab = await browser.tabs.query({currentWindow: true, active: true});
    tab.then(function(tabb){
        test = tabb[0].url.toString()
    });
    return test;
}

async function getURL() {
    var tab = await browser.tabs.query({currentWindow: true, active: true});
    return tab[0].url;
}

    console.log(url.toString()); // Promise
}

The first function get rejected the second one is fullfilled.


Solution

  • I would like get a value from a promise but dont know how.

    The only way to get a value from a promise is by using .then() on the promise or within the same function, you can use await.

    An async function always returns a promise. Within a function, you can use await to "wait" for a promise to get the value, but that is not the case for the return value for the function. The function always returns a promise and you always use either await or .then() to get the value from a promise.

    So, your second getURL() function returns a promise who's resolved value is the url you want. To get that value, you use .then() on the returned promise:

    async function getURL() {
        var tab = await browser.tabs.query({currentWindow: true, active: true});
        return tab[0].url;
    }
    
    getURL().then(url => {
        console.log(url);
    });
    

    Or, there's really no big advantage in using await here so you could also just do:

    function getURL() {
        return browser.tabs.query({currentWindow: true, active: true}).then(tab => {
            return tab[0].url;
        });
    
    }
    
    getURL().then(url => {
        console.log(url);
    });
    

    Your first version of getURL() does not work because your function returns BEFORE your .then() handler is called and thus you always just return "".