第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

.map 函數(shù)中的異步驗(yàn)證

.map 函數(shù)中的異步驗(yàn)證

回首憶惘然 2023-05-18 10:49:17
我正在使用 Node JS、Sequelize 和 Postgres 數(shù)據(jù)庫(kù)開(kāi)發(fā)應(yīng)用程序的后端。注冊(cè)課程時(shí),用戶(hù)必須告知哪些組織、公司和教師將與其相關(guān)聯(lián)。組織 ID 通過(guò)數(shù)組傳遞到后端,我正在嘗試進(jìn)行檢查以確保傳遞的 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貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊

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


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


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這是一個(gè)重構(gòu)版本,通過(guò)在一個(gè)查詢(xún)中獲取所有內(nèi)容然后進(jìn)行檢查/創(chuàng)建插入,速度會(huì)更快一些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 }); 

}


查看完整回答
反對(duì) 回復(fù) 2023-05-18
?
翻過(guò)高山走不出你

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊

如果你有一個(gè) ID 數(shù)組并且你想檢查它們是否存在你應(yīng)該使用 (in) 運(yùn)算符,這使得你只訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)一次并一次獲取所有記錄(而不是獲取它們一個(gè)一個(gè)循環(huán)),在你得到這些記錄后,你可以檢查它們的長(zhǎng)度以確定它們是否都存在。


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

let foundOrgs = await Organization.findAll({

  where: {

    id: {

      [Op.in]: organizationsArray,

    }

  }

});


查看完整回答
反對(duì) 回復(fù) 2023-05-18
  • 2 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)