简体   繁体   中英

Javascript async/await on promise return pending, how to get the value instanly?

I build chrome extension with javascript. here is my code :

async function getlocalstorage() {
    var theresult = '';
    await new Promise(function(resolve, reject){
        chrome.runtime.sendMessage({action:'getlocalstorage',data:"version"}, function(response){
            if (response.data!=='null') {
                theresult = resolve(response.data);
            } else {
                theresult = reject(response.data);
            }
        });
    })
    return theresult;
}

window.onload = function (){
    console.log('this should be the first output');
    /*it's returning pending status*/
    console.log(getlocalstorage());
    console.log('this should be the last output');
}

but the return of console.log(getlocalstorage()); is pending status . . . how to do that ?

You can't get the value instantly because getlocalstorage is asynchronous, but you can write to the console in the order in which you are expecting. Make the onload function async and await the value of getlocalstorage() :

window.onload = async function (){
    console.log('this should be the first output');
    console.log(await getlocalstorage());
    console.log('this should be the last output');
}

What console.log(getlocalstorage()); print is a promise.Your getlocalstorage function actually return a promise and has ignored the return statement. You need to wait for it to resolve. You need to add the keyword before the function call: console.log( getlocalstorage()); 关键字: console.log( getlocalstorage());

By the way, you can await on a promise directly. Here is an example of getting the current active tab using async/await.

let getActiveTabAsync = () => {
  return new Promise(function(resolve, reject) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      let { lastError } = chrome.runtime
      if (typeof lastError !== 'undefined') reject(lastError);
      else resolve(tabs[0]);
    });
  });
}
let activeTab = await getActiveTabAsync()
console.log(`The current active tab id is ${activeTab.id}`)

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