我试图在另一个映射函数中映射一个数组,但我的代码未同步运行

时间:2019-04-06 12:31:44

标签: javascript node.js ecmascript-6 async-await es6-promise

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

2 个答案:

答案 0 :(得分:1)

您的代码中有些错误:

  1. 您可以构建new Promise,尽管不必这样做;如果您要包装的回调函数,只需构造一个即可。

  2. 您确实调用了两个带有回调的函数,但没有将它们包装在new Promise中。

  3. await.map的结果;总是无操作,因为.map返回一个数组,而await仅适用于Promises。如果您有一个诺言数组,则可以使用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
    }
  }
}

答案 1 :(得分:0)

  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
}