我试图让MedGuideURL在第二个回调中使用,但它的值为空,似乎第二个回调总是在第一个回调完成之前发生。我正在考虑使用Promise / Observable,但是有没有更简单的方法?
currentBulletinArray = bulletinArray.filter({bulletin -> Bool in
let doesCategoryMatch = getScopeFilters(issued: true, scopes: scope, bulletin: bulletin, signature: true)
if searchBarIsEmpty(){
return doesCategoryMatch
} else {
return doesCategoryMatch && (bulletin.bulletinVersion?.bulletin?.name?.lowercased().contains(searchText.lowercased()))!
}
})
答案 0 :(得分:2)
您需要首先了解
async
的行为。您必须在方法完成之前进行回调
您可以凭承诺更改get
示例
如果使用sendResis
承诺方法
exports.handler = function (event, context, callback) {
var path = event.path;
var drugId = path.replace(/\//g, '');
var MedGuideURL = "";
var params = {
TableName: 'QRCodeInfo',
Key: {
"DrugId": drugId
}
};
docClient.get(params).promise().then((data) => {
console.log('success' + x);
console.log("The data is: " + data.Item.MedGuideURL);
MedGuideURL = data.Item.MedGuideURL;
return sendRes(200, MedGuideURL); //if sendResis promise method
}).then((finalResponse) => {
callback(null, finalResponse);
})
.catch((err) => {
callback(err, null);
})
};
如果不能保证sendResis:
exports.handler = function (event, context, callback) {
var path = event.path;
var drugId = path.replace(/\//g, '');
var MedGuideURL = "";
var params = {
TableName: 'QRCodeInfo',
Key: {
"DrugId": drugId
}
};
docClient.get(params).promise().then((data) => {
console.log('success' + x);
console.log("The data is: " + data.Item.MedGuideURL);
MedGuideURL = data.Item.MedGuideURL;
let finalResponse = sendRes(200, MedGuideURL); //if sendResis not promise method
return callback(null, finalResponse);
})
.catch((err) => {
callback(err, null);
})
};