[英]nodejs async function not returning
我有一個功能。 在此功能內,我檢查是否驗證了令牌,向Facebook發送一個http請求,以及向我的雲服務器發送另一個http請求。
function myAsyncFunction(token,fbat){
if (token) {
jwt.verify(token, jwt_secret, {
issuer: 'me@me.com'
}, function(err, decoded) {
if (err) {
if (err.name === 'TokenExpiredError') {
console.log('Token expired'); // renew token
var options = {
hostname: 'graph.facebook.com',
port: 443,
//path: '/oauth/?appsecret_proof='+hash+'&access_token='+at,
path: '/v2.5/me?fields=id&access_token=' + fbat,
method: 'GET'
}; //end of options
var callback = function(response) {
var str = '';
//another chunk of data has been received, so append it to `str`
response.on('data', function(chunk) {response on;
str += chunk;
});
response.on('end', function() { //start of response end;
var json = JSON.parse(str);
if (json.hasOwnProperty('id')) {
var params = {
TableName: 'Users',
Key: {
'fid': {
'N': json.id.toString()
}
},
ConsistentRead: false,
ProjectionExpression: 'fid,st'
};
dynamodb.getItem(params, function(err, data) {
if (err) {
return false;
} else { //start of dynamodb else
if (isEmptyObject(data)) {
return false;
}
else {
if (data.Item.st.S === 't') {
return true;
} else {
return false;
}
}
}
});
}
else {
return false;
};
});
response.on('error', function() {
return false;
});
};
https.request(options, callback).end();
} else if (err.name === 'JsonWebTokenError') {
return false;
} else {
return false;
}
} else {
return true;
}
});
} else {
return false;
}
return false;
};
然后,我嘗試調用此函數:
myAsyncFunction(token, fbat, function(result){
if(result){
//do some network calls here
}
else{
//do some other network calls here
}
});
當我調用異步函數進行調試時,它正在對Facebook和我的服務器進行調用,問題是它沒有返回任何內容。 它到達了return語句的地步,但是檢查結果是true還是false的條件永遠不會執行。
您的myAsyncFunction
僅接受兩個參數: function myAsyncFunction(token,fbat) { ... }
。 因此,在調用時傳遞的回調將永遠無法執行。 同樣,異步函數中的各種return
語句也不會達到預期的效果。
我建議閱讀node.js / javascript的回調樣式。
您最終要尋找的是這樣的:
function myAsyncFunction(token, fbat, callback) {
someOtherasyncFunction(arg1, arg2, function(err, result) {
if (err) {
return callback(err); // propagate error
}
yetAnotherAsyncFunction(argA, argB, function(err, result2) {
if (err) {
return callback(err); // propagate error
}
// do something with result2...
callback(null, myResult); // result2 is the result being passed into the callback
});
});
}
現在,當您調用函數時:
myAsyncFunction(token, fbat, function(err, result) {
if (err) {
// handle error... something has gone wrong...
}
// do something with the result...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.