У меня есть массив сведений о потенциальных покупателях (которые мне нужно вставить в БД), и у каждого из них есть поле по имени интереса, которое представляет собой массив строк, я должен найти каждую интересующую область, и если будет найдена интересующая область из БД,мне нужно будет сохранить ObjectId интересаrea, иначе мне нужно будет создать новый интересаrea в БД и сохранить его objectIds в InterestArea в качестве поля отведения
Мой ввод
let jsonArray = [ { firstName: 'newLead1',
lastName: 'newLead1',
company: 'hub',
companySize: '22',
designation: 'software Enginner',
phoneNumber: '1234567890',
jobRole: 'engineer',
email: 'newLead1@hub.com',
leadSource: 'online',
industry: 'it',
location: 'ernakulam',
annualTurnOver: '10',
requestedMeetingDate: '2019-03-28T09:13:02.958Z',
interestArea: 'app,newspaper' },
{ firstName: 'newLead2',
lastName: 'Sharma',
company: 'hub',
companySize: '20',
designation: 'software Enginner',
phoneNumber: '1234567891',
jobRole: 'engineer',
email: 'newLead2@hub.com',
leadSource: 'web',
industry: 'software',
location: 'kacherippady',
annualTurnOver: '15',
requestedMeetingDate: '2019-03-28T09:13:02.958Z',
interestArea: 'website,newspaper' } ]
Ниже приведена функция, которую я пробовал
function jsonArrayMap(jsonArray){
return new Promise(function(resolve,reject){
let validateInFn = [];
(async ()=>{
validateInFn = await jsonArray.map(lead => {
(async ()=>{
console.log("step: 1");
console.log("interestArea is present",lead.interestArea);
let interestAreaArray = lead.interestArea.split(',');
console.log("interestAreaArray",interestAreaArray);
let interestAreaObjectIdArrayInFn = await interestAreaArray.map(interestArea => {
console.log("step: 2");
console.log("each word interestArea",interestArea)
InterestArea.find({where:{name:interestArea}},(err,interestAreaInDb)=>{
console.log("step: 3");
console.log("search in db got interestAreaInDb",interestAreaInDb);
if(interestAreaInDb.length>0) {
console.log("step: 4");
return interestAreaInDb[0].id
}
else {
console.log("step: 4");
InterestArea.create({name:interestArea},(err,newInterestArea)=>{
return newInterestArea.id
});
} //else
}) //find is there an interestArea with this name
}) //interestAreaArray.map
console.log("interestAreaObjectIdArrayInFn",interestAreaObjectIdArrayInFn)
})();
})
console.log("validateInFn",validateInFn)
})();
}) //promise
} //jsonArrayMap
Вывод был
step: 1
interestArea is present app,newspaper
interestAreaArray [ 'app', 'newspaper' ]
step: 2
each word interestArea app
step: 2
each word interestArea newspaper
step: 1
interestArea is present website,newspaper
interestAreaArray [ 'website', 'newspaper' ]
step: 2
each word interestArea website
step: 2
each word interestArea newspaper
interestAreaObjectIdArrayInFn [ undefined, undefined ]
interestAreaObjectIdArrayInFn [ undefined, undefined ]
validateInFn [ undefined, undefined ]
step: 3
search in db got interestAreaInDb [ { name: 'app', id: 5ca799d2491c0cd8f415f980 } ]
step: 4
(node:56798) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated
step: 3
search in db got interestAreaInDb []
step: 4
step: 3
search in db got interestAreaInDb [ { name: 'website', id: 5ca799d2491c0cd8f415f981 } ]
step: 4
step: 3
search in db got interestAreaInDb []
step: 4
Я быложидая, что код будет ждать в тех местах, где я его использовал, но он не сработал, как я ожидал
Я также попытался использовать async npm
я использовал их функцию forEachOf, которая также не работала
Ниже приведена функция, которую я пробовал
function jsonArrayMap(jsonArray){
return new Promise(function(resolve,reject){
let validateInFn = [];
async.forEachOf(jsonArray, (lead, key, callbackforEachOfjsonArray) => {
console.log("step: 1");
console.log("interestArea is present",lead.interestArea);
let interestAreaArray = lead.interestArea.split(',');
console.log("interestAreaArray",interestAreaArray);
let interestAreaObjectIdArrayInFn = [];
async.forEachOf(interestAreaArray, (interestArea, key2, callbackforEachOfInterestAreaArray) => {
console.log("step: 2");
console.log("each word interestArea",interestArea)
InterestArea.find({where:{name:interestArea}},(err,interestAreaInDb)=>{
console.log("step: 3");
console.log("search in db got interestAreaInDb",interestAreaInDb);
if(interestAreaInDb.length>0) {
console.log("step: 4");
interestAreaObjectIdArrayInFn.push(interestAreaInDb[0].id)
if(interestAreaArray.length -1 == key2) callbackforEachOfInterestAreaArray()
}
else {
console.log("step: 4");
InterestArea.create({name:interestArea},(err,newInterestArea)=>{
interestAreaObjectIdArrayInFn.push(newInterestArea.id)
if(interestAreaArray.length -1 == key2) callbackforEachOfInterestAreaArray()
});
} //else
}) //find is there an interestArea with this name
}, function (err,result2) {
console.log("result2",result2)
if(jsonArray.length -1 == key) callbackforEachOfjsonArray()
})
},function (err,result) {
console.log("result",result)
})
}) //promise
} //jsonArrayMap
Вывод был
step: 1
interestArea is present app,newspaper
interestAreaArray [ 'app', 'newspaper' ]
step: 2
each word interestArea app
step: 2
each word interestArea newspaper
step: 1
interestArea is present website,newspaper
interestAreaArray [ 'website', 'newspaper' ]
step: 2
each word interestArea website
step: 2
each word interestArea newspaper
step: 3
search in db got interestAreaInDb [ { name: 'app', id: 5ca799d2491c0cd8f415f980 } ]
step: 4
(node:56939) [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated
step: 3
search in db got interestAreaInDb [ { name: 'newspaper', id: 5ca894c3aa7a64dddefa2674 } ]
step: 4
step: 3
search in db got interestAreaInDb [ { name: 'website', id: 5ca799d2491c0cd8f415f981 } ]
step: 4
step: 3
search in db got interestAreaInDb [ { name: 'newspaper', id: 5ca894c3aa7a64dddefa2674 } ]
step: 4