我想知道是否有办法避免在我的解析器中进行不必要的调用。
我的解析器看起来像这样:(最小化)
// request read access to the external storage if we don't have it
cordova.plugins.diagnostic.getExternalStorageAuthorizationStatus(function (status) {
if (status === cordova.plugins.diagnostic.permissionStatus.GRANTED) {
console.log("External storage use is authorized");
} else {
cordova.plugins.diagnostic.requestExternalStorageAuthorization(function (result) {
console.log("Authorization request for external storage use was " + (result === cordova.plugins.diagnostic.permissionStatus.GRANTED ? "granted" : "denied"));
}, function (error) {
console.error(error);
});
}
}, function (error) {
console.error("The following error occurred: " + error);
});
如果我用这样的话来查询:
Transaction: {
bkFrom(transaction) {
return transaction.getFrom(); //<-- CACHE THIS?
},
bkTo(transaction) {
return transaction.getTo(); //<-- CACHE THIS?
},
type(transaction) {
return new Promise(async function(resolve, reject) {
const [From, To] = await Promise.all([
transaction.getFrom(), //<-- CACHE THIS? If bkFrom() is already triggered
transaction.getTo(), //<-- CACHE THIS? If is bkTo() already triggered
]);
switch (true) {
case From.isKonto && To.isKonto:
resolve(TransactionType.INTERN);
case !From.isKonto && To.isKonto:
resolve(TransactionType.INCOMING);
case From.isKonto && !To.isKonto:
resolve(TransactionType.OUTGOING);
default:
resolve(null);
}
});
},
},
它会拨打getTansactions(limit: 10) {
type
bkFrom {
id
name
isKonto
}
bkTo {
id
name
isKonto
}
}
和transaction.getFrom();
两次。有没有办法避免两次打电话?像“缓存”,如果它来自同一个请求?
答案 0 :(得分:0)
同一类型字段的解析器将并行执行,因此type
的解析器无法知道bkFrom
解析的解析器是什么。我认为处理此问题的最佳方法是将该逻辑提升一级,进入getTansactions
的解析器。
getTransactions: async () {
// Get the transactions first
const transactions = await someCallToGetTransactions()
// Grab all our additional calls and use Promise.all to call them concurrently
const promises = transactions.reduce((memo, t) => {
memo.push(t.getTo())
memo.push(t.getFrom())
return memo
}, [])
const toFrom = await Promise.all(promises)
// Merge the results into one array
return transactions.map((t, index) => {
const bkTo = toFrom[index * 2]
const bkFrom = toFrom[(index * 2) + 1]
const type = getType(bkTo, bkFrom) //calculate type from your other fields
return Object.assign({}, t, { bkTo, bkFrom, type })
})
}
或者,您可以返回Transaction类的实例,并以这种方式缓存getTo()
和getFrom()
的值:
class Transaction {
async getTo () {
if (!this._to) {
this._to = await //whatever
}
return this._to
}
}
这样,第一次调用getTo()
时,它将获取值并将其保留在内存中。对它的任何后续调用(对于同一个实例)只会从内存中返回值。