0
我正在請求站點上的項目,我需要檢查主題的描述是否包含單詞「purchsed」,然後纔將其保存到數據庫。我應該用Promise解決這個問題嗎?
所以,當我做一些事情liek此:
items.forEach(function(item) {
if(!isPurchased)
saveToDb(item)
}
但它不工作(項目保存在任何情況下),因爲函數在IF語句(isPurchased)提供返回undefined(因爲異步節點行爲,我認爲)。
所以,我寫承諾notPurchased:
function notPurchased(advert) {
return new Promise(
function(resolve, reject) {
if (description.length == 0)
resolve();
return request('adverts', {'count' : 50}, function(resp) {
for (i = 0; i < resp.count; i++) {
if(resp.response.items[i].text.match('purchased') != null)
reject('This item has been purchased!');
}
resolve();
});
});
}
,然後使用這個承諾在forEach循環:
response.items.forEach(function(item) {
notPurchased(item).then(function() {
DB.storeItem(item);
});
});
這是一個很好的形式給出?我沒有足夠的NodeJS經驗,在我看來,定義一個簡單的bool函數的承諾有點棘手。