簡體   English   中英

在映射數組時將異步函數的結果包含在我的“返回”中

[英]Including the results of an async function in my 'return' while mapping an array

問題

我試圖在映射數組時調用數據庫函數。 我創建了一些示例代碼來在較小的范圍內演示我的問題。 我正在使用 'mysql2' 和 'sequelize' 依賴項,以及 MySQL Workbench。

示例代碼中的目標

我的數據庫中有兩個表——一個叫做“boxes”,一個叫做“items”。 每個項目都將在一個框中(它將具有“box_id”的屬性)。 每個盒子都有一個位置。 我想得到一個對象數組,它只顯示項目的名稱和它所在的盒子的位置(不僅僅是 ID)。 我希望它以最干凈的方式運行。 我知道有一種方法可以將這兩個數據庫聯系在一起,並且我會很感激如何做到這一點,但我覺得我會使用不同的方法學習更重要的概念 - 所以理想情況下,我想要一個替代解決方案。

代碼

mainFunction() 是起點

// Gets all items currently in my database and returning the dataValues
const getAllItems = async () => {
    const findAllItems = await Item.findAll()
    const items = findAllItems.map(item => item.dataValues)
    return items
}

// Gets a box from my database, by ID, and returning its dataValues
const getOneBox = async (id) => {
    const findOneBox = await Box.findOne({ where: {id}})
    return findOneBox.dataValues
}

// Starting point
const mainFunction = async () => {
// Get all items in database
    const items = await getAllItems()

// Go through each item, and everytime, get the box that corresponds to the item's box_id
    const myArray = items.map(async item => {
        const getBox = await getOneBox(item.box_id)
// Return an object with my custom formatting, and including the box's location
        return {
            itemID: item.id,
            itemName: item.name,
            itemLocation: getBox.location
        }
    })

// The function will only work if I manually give my function enough time to finish
    console.log('myArray before delay => ', myArray)
    await new Promise(response => setTimeout(response, 500))
    console.log('myArray after delay => ', myArray)
}

這是我終端中的結果:

在此處輸入圖片說明

設置

如果重要的話,這是我的設置。 我手動填充了我的表格以簡化事情:

項目 => 物品

盒子 => 盒子

// Populating the existing 'test' schema with relevant tables and running main function after connecting
const Sequelize = require('sequelize')
const database = new Sequelize ('test', 'root', [REDACTED], {
    host: 'localhost',
    dialect: 'mysql',
    define: {
        timestamps: false
    }
})
const connect = async () => {
    await database.authenticate()
    .then(async () => {
        await database.sync()
        console.log('Connected...')
        mainFunction()
    }).catch(error => {
        console.log('Failed to connect => ', error)
    })
}
connect()


// Defining my models
const Box = database.define('box', {
    name: Sequelize.STRING,
    location: Sequelize.STRING
})
const Item = database.define('item', {
    name: Sequelize.STRING,
    box_id: Sequelize.INTEGER
})

原來問題出在我的方法上; 使用 for 循環實際上很容易。 我會留下我的解決方案,以防它對任何人有幫助。

這個只是向我的 items 數組添加了另一個屬性

const mainFunction = async () => {
    const items = await getAllItems()
    for(i = 0; i < items.length; i++) {
        const getBox = await getOneBox(items[i].box_id)
        items[i]['location'] = getBox.location
    }
    console.log(items)
}

在此處輸入圖片說明

這個是為了如果我想以我自己的方式格式化它

const mainFunction = async () => {
    const items = await getAllItems()
    const itemsFormatted = []
    for(i = 0; i < items.length; i++) {
        const getBox = await getOneBox(items[i].box_id)
        itemsFormatted.push({
            itemID: items[i].id,
            itemName: items[i].name,
            itemLocation: getBox.location
        })
    }
    console.log(itemsFormatted)
}

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM