2017-05-24 2 views
0

javascriptでクロム拡張子をビルドします。私のコードはここにあります:Javascript非同期/約束を返すことを待っている、値を取得する方法instanly?

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'); 
} 

ですが、console.log(getlocalstorage());保留状態です。 。 。どうやってするか ?

+0

もしかして:のawait –

答えて

0

getlocalstorageは非同期ですが、瞬時に値を取得することはできませんが、期待どおりの順序でコンソールに書き込むことができます。 onload機能asyncを作成し、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'); 
} 
関連する問題