我正在尝试在另一个映射函数中映射一个数组,我的代码没有同步运行



我有一个潜在客户详细信息数组(我需要将其插入到数据库中(,并且每个潜在客户都有一个名为 interestArea 的字段,这是一个字符串数组,我必须找到每个 interestArea,如果从数据库中找到 interestArea,我将不得不存储 interestArea 的 ObjectId,否则我将不得不在 db 中创建新的 interestArea 并将其 objectId 存储在 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

期待代码在我使用它的地方等待,但它没有像我预期的那样工作

我也尝试使用异步 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

你的代码中有一些错误:

  1. 尽管您不必构造一个new Promise;如果您有一个包装的回调,只需构造一个。

  2. 您确实调用了两个接受回调的函数,但不会将它们包装在new Promise中。

  3. await .map的结果;这总是一个无操作,因为.map返回一个数组,await只对承诺起作用。如果你有一个承诺数组,你可以使用Promise.all并将其转换为解析为数组的承诺;然后你可以await


现在,您的代码无法轻松修复。因此,让我们从头开始。

首先,让我们将回调包装成 promises:

const findInterestArea = (name) => 
  new Promise((resolve, reject) => InterestArea.find({where: { name }}, (err, result)=> err ? reject(err) : resolve(result));
const createInterestArea = (name) => 
  new Promise((resolve, reject) => InterestArea.create({ name }, (err, result) => err ? reject(err) : resolve(result));

现在,抽象的下一步将是findOrInsert操作:

async function findOrCreateInterest(name) {
  const exists = await findInterestArea(name);
  if (exists) return exists;
  return await createInterestArea(name);
}

现在,您可以轻松遍历jsonArray和每个interestArea并插入它:

async function jsonArrayMap(jsonArray) {
  for(const lead of jsonArray) {
    const interests = lead.interestArea.split(',');
    for (const interest of interests) {
      const { id } = await findorCreateInterest(interest);
      // do stuff with id
    }
  }
}
  async function jsonArrayMap(jsonArray) {
    let leads = [];
    let newInterestArrayOfObjectIds = [];
   for(const lead of jsonArray) {
      const interests = lead.interestArea.split(',');
      for(const interest of interests) {
        const { id } = await findorCreateInterest(interest);
        newInterestArrayOfObjectIds=id;
      }
      leads.push({
                  firstName:lead.firstName,lastName:lead.lastName,
                  company:lead.company,companySize:Number(lead.companySize.replace(/,/g,'')),
                  designation:lead.designation,phoneNumber:lead.phoneNumber,
                  jobRole:lead.jobRole,email:lead.email,
                  leadSource:lead.leadSource,industry:lead.industry,
                  location:lead.location,annualTurnOver:Number(lead.annualTurnOver.replace(/,/g,'')),
                  interestArea:(lead.interestArea)? newInterestArrayOfObjectIds : [],
                  reqestedMeetingDate:(lead.requestedMeetingDate)? new Date(lead.requestedMeetingDate) : undefined,
                  csvTracker:csvTracker
                  })
   }
   return leads
}
async function createLead () =>{
  let leads = await jsonArrayMap(jsonArray);
    let mat = await LeadCollection.aggregate([
      //i have to do some aggregations here
    ]).toArray();
    //then only i can insert lead here
}

最新更新