简体   繁体   中英

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.

async function returns promise so you can only get promise as a result. so do

var url = getUrl()
url.then((resp) => {console.log(resp)}); 

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 "" .

async and await - these resolve promises and give you value directly. Remove await and .then works.

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