[英]Async function returns value, shows up on console, but undefined elsewhere
异步函数返回可以登录到控制台的值,但在其他地方未定义
函数调用:
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 天才把它贴在这里。
感谢您的帮助。
我对我的函数定义进行了一些更改并且它起作用了
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...'); }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.