Chrome扩展/cookie/等待回调函数

pti*_*ste 2 javascript cookies google-chrome-extension async-await

嗨,我很抱歉问这个问题,我做了很多研究,但我无法解决这个问题,我无法获取我的 cookie 的值,我认为这是因为我的函数有一个回调,(我在我的代码)但我不知道修复它:/

const cookieUrl = 'http://urlCookie'
const cookieName = 'CookieName'

cookieValue = checkCookie(cookieUrl,cookieName)
console.log('cookieValue: ', cookieValue)

function checkCookie(url, name){
    chrome.cookies.get({
        url: url,
        name: name
    },
    function (cookie) {
        if (cookie) {
        console.log(cookie.value)
        return cookie.value
        }
        else {
        console.log('Can\'t get cookie! Check the name!')
        return 0
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

Toa*_* Ho 5

大多数 Chrome API 在我们调用它们时不会返回 Promise,我们必须为其提供回调来处理响应。因此,在这种情况下,我们可以添加一个 Promise 并在回调中解析它,这样当 chrome 调用回调时我们就可以收到信号。

const cookieUrl = 'http://urlCookie'
const cookieName = 'CookieName'

cookieValue = checkCookie(cookieUrl,cookieName)
    .then((cookie) => console.log(cookie))
    .catch(function(error) {console.log(error)});

function checkCookie(url, name){
    return new Promise((resolve, reject) => {
        chrome.cookies.get({
            url: url,
            name: name
        },
        function (cookie) {
            if (cookie) {
                console.log(cookie.value)
                resolve(cookie.value)
            }
            else {
                console.log('Can\'t get cookie! Check the name!')
                reject(0);
            }
        })
    });
}
Run Code Online (Sandbox Code Playgroud)