亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

.map 函數中的異步驗證

.map 函數中的異步驗證

回首憶惘然 2023-05-18 10:49:17
我正在使用 Node JS、Sequelize 和 Postgres 數據庫開發應用程序的后端。注冊課程時,用戶必須告知哪些組織、公司和教師將與其相關聯。組織 ID 通過數組傳遞到后端,我正在嘗試進行檢查以確保傳遞的 ID 存在。到目前為止我所做的是:const { organizations } = req.body;const organizationsArray = organizations.map(async (organization) => {? const organizationExists = await Organization.findByPk(organization);? if (!organizationExists) {? ? return res? ? ? .status(400)? ? ? .json({ error: `Organization ${organization} does not exists!` });? }? return {? ? course_id: id,? ? organization_id: organization,? };});await CoursesOrganizations.bulkCreate(organizationsArray);
查看完整描述

2 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

正在Array.map()返回一個承諾數組,您可以使用Promise.all(). 在地圖內部,您應該使用throw new Error()break out of map - 將引發此錯誤Promise.all(),然后您可以捕獲它并將錯誤返回給客戶端(或吞下它等)。


這是您的模式的更正版本,解決了 Promise 結果。


const { organizations } = req.body;

try {

  // use Promise.all to resolve the promises returned by the async callback function

  const organizationsArray = await Promise.all(

    // this will return an array of promises

    organizations.map(async (organization) => {

      const organizationExists = await Organization.findByPk(organization, { 

        attributes: ['id'], // we only need the ID

        raw: true, // don't need Instances

      });

      if (!organizationExists) {

        // don't send response inside the map, throw an Error to break out

        throw new Error(`Organization ${organization} does not exists!`);

      }

      // it does exist so return/resolve the value for the promise

      return {

        course_id: id,

        organization_id: organization,

      };

    })

  );


  // if we get here there were no errors, create the records

  await CoursesOrganizations.bulkCreate(organizationsArray);


  // return a success to the client

  return res.json({ success: true });

} catch (err) {

  // there was an error, return it to the client

  return res.status(400).json({ error: err.message }); 

}

Organizations這是一個重構版本,通過在一個查詢中獲取所有內容然后進行檢查/創建插入,速度會更快一些Course。


const { Op } = Sequelize;

const { organizations } = req.body;

try {

  // get all Organization matches for the IDs

  const organizationsArray = await Organization.findAll({

    attributes: ['id'], // we only need the ID

    where: {

      id: {

        [Op.in]: organizations, // WHERE id IN (organizations) 

      }

    },

    raw: true, // no need to create Instances

  });


  // create an array of the IDs we found

  const foundIds = organizationsArray.map((org) => org.id);


  // check to see if any of the IDs are missing from the results

  if (foundIds.length !== organizations.length) {

    // Use Array.reduce() to figure out which IDs are missing from the results

    const missingIds = organizations.reduce((missingIds, orgId) => {

      if (!foundIds.includes(orgId)){

        missingIds.push(orgId);

      }

      return missingIds;

    }, []); // initialized to empty array


    throw new Error(`Unable to find Organization for: ${missingIds.join(', ')}`);

  }


  // now create an array of courses to create using the foundIds

  const courses = foundIds.map((orgId) => {

    return {

      course_id: id,

      organization_id: orgId,

    }; 

  });


  // if we get here there were no errors, create the records

  await CoursesOrganizations.bulkCreate(courses);


  // return a success to the client

  return res.json({ success: true });

} catch (err) {

  // there was an error, return it to the client

  return res.status(400).json({ error: err.message }); 

}


查看完整回答
反對 回復 2023-05-18
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

如果你有一個 ID 數組并且你想檢查它們是否存在你應該使用 (in) 運算符,這使得你只訪問數據庫一次并一次獲取所有記錄(而不是獲取它們一個一個循環),在你得到這些記錄后,你可以檢查它們的長度以確定它們是否都存在。


const { Op } = require("sequelize");

let foundOrgs = await Organization.findAll({

  where: {

    id: {

      [Op.in]: organizationsArray,

    }

  }

});


查看完整回答
反對 回復 2023-05-18
  • 2 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號