chrome.storage.local get返回“未定义”

时间:2019-02-12 08:04:44

标签: javascript google-chrome-extension callback promise

我想通过chrome.storage.local.get()从chrome存储中获取2个值,但是如果我尝试从回调函数返回这些值,则会得到'undefined'。如果我用console.log()记录它们,则它们实际上已被记录。这是为什么?我读过其他一些文章,我需要使用回调-但就我对JS的基本理解而言,我已经从get()的回调函数返回值。

// this should load 2 keys from an object stored in chrome storage
function loadJiraUrlElements(){
    chrome.storage.local.get({companyName: '', jiraBaseUrl: ''}, function(items) {
        return (items.companyName + items.jiraBaseUrl);
     })
}

// I want to use this function to call the return value and populate a DOM element
function populateUrlFieldsWithUrlElements(){
    companyInput.value = loadJiraUrlElements()
}

2 个答案:

答案 0 :(得分:2)

之所以得到undefined,是因为您要返回的回调函数(即内部函数),而不是外部函数,是要从中获取返回值的外部函数。

您可以在resolve中使用promise,以便可以在.then函数中使用populateUrlFieldsWithUrlElements回调来获取所需的值:

function loadJiraUrlElements() {
  return new Promise(resolve => {
    chrome.storage.local.get({companyName: '', jiraBaseUrl: ''}, function(items) {
      resolve(items.companyName + items.jiraBaseUrl);
    })
  })
}

// I want to use this function to call the return value and populate a DOM element
function populateUrlFieldsWithUrlElements() {
  loadJiraUrlElements().then(result => {
    companyInput.value = result;
  })
}

或者,如果您不想使用async回调,则可以在第二个函数中使用await / .then

// I want to use this function to call the return value and populate a DOM element
async function populateUrlFieldsWithUrlElements() {
  companyInput.value = await loadJiraUrlElements();
}

答案 1 :(得分:0)

这是一个async函数,您可以将其包装在Promise对象下,也可以继续使用回调机制。

1。)承诺:

function loadJiraUrlElements() {
    return new Promise(function(resolve, reject) {
        chrome.storage.local.get({companyName: '', jiraBaseUrl: ''}, function(items) {
            resolve(items.companyName + items.jiraBaseUrl);
         })
    });
}

// And caller function changes to 
function populateUrlFieldsWithUrlElements(){
    loadJiraUrlElements().then(function(value) {
        companyInput.value = value;
    })
}

2。)回调:

function loadJiraUrlElements(cb){
    chrome.storage.local.get({companyName: '', jiraBaseUrl: ''}, function(items) {
        cb && cb(items.companyName + items.jiraBaseUrl);
     })
}

function populateUrlFieldsWithUrlElements(){
    loadJiraUrlElements(function(value) {
        companyInput.value = value;
    })

}