【问题标题】:Async function returns value, shows up on console, but undefined elsewhere异步函数返回值,显示在控制台上,但在其他地方未定义
【发布时间】:2020-03-26 19:44:16
【问题描述】:

异步函数返回的值可以在控制台登录,但在其他地方未定义

函数调用:

getData(msg.queryCountry, new Date(), 3, function callback(data){
            console.log('call back func:', data); //works
            
            console.log(data[0].name); // works
            chrome.runtime.sendMessage(sender.id,{'cdata':data}); //doesn't work; 'undefined' received on receiver's end
        })
        .then( response =>{
                //console.log('response:', response);
                console.log('retrieval successful...');
        })
        .catch( err => {
                console.error(err);
        });

功能定义:

async function getData(country, date, level, callback){
   
 let response = await fetch(url);
 let rawdata = await response.text();

 if(response.status == 200 && response.ok == true){
   
  console.log('Response: 200 OK');

   //extracts the data for the country from .csv file received
   let countryUpdate = extractDailyUpdate(rawdata, country);

   callback(countryUpdate);
   
  }

else {
  if(level >= 0){
   //Try again with previous date
    getData(country, prevDate(date, 1), level - 1, callback);
  }
  else {console.log('Ran out of attempts...'); }
    }   
}

输出:

console.log('call back function:', data); 显示接收到的数据,但是当我发送数据时,chrome.runtime.sendMessage(sender.id,{'cdata':data}); 在接收端显示为“未定义”。

我知道我混淆了异步函数,将其视为同步;挣扎了4天才发到这里。

非常感谢您的帮助。

【问题讨论】:

    标签: javascript google-chrome-extension callback async-await


    【解决方案1】:

    我对我的函数定义做了一些更改,它起作用了

     async function getData(country, date, level, callback){
    
    
     let response = await fetch(url);
     let rawdata = await response.text();
    
     if(response.status == 200){
    
      console.log('Response: 200 OK');
    
       //Removed this line and to be handled separately 
       //let countryUpdate = extractDailyUpdate(rawdata, country);
    
       callback(rawdata);
    
      }
    
    else {
      if(level >= 0){
       //Try again with previous date
        getData(country, prevDate(date, 1), level - 1, callback);
      }
      else {console.log('Ran out of attempts...'); }
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多