【问题标题】:Return resolved promise返回已解决的承诺
【发布时间】:2021-05-25 16:18:15
【问题描述】:

我的strapi中有一个函数,我可以在其中映射数据并在其中运行另一个查询。

async search(ctx) {
    const authors = [
        {
            id: 1,
            name: "author 1"
        },
        {
            id: 2,
            name: "author 2"
        },
    ]

    authors.map((data, i) => {
        var books = this.getBooks(data.id)
        console.log(books)

        // some stuffs here
    })
},

getBooks: async function (authorId) {
    return await strapi.query('books').find({ userId: authorId })
}

console.log('books') 显示 Promise { <pending> }。我对承诺的东西不是很熟悉,但我尝试了类似下面的方法,但我猜这不是正确的方法。它仍在返回相同的未决承诺。

getBooks: async function (authorId) {
    const books = await strapi.query('books').find({ userId: authorId })
    return Promise.resolve(books)
}

【问题讨论】:

  • 尝试在 getBooks 函数中只返回书籍。
  • 如果我只返回书籍,那与我在第一个代码块中的原始功能没有区别。

标签: promise strapi resolve


【解决方案1】:

发现此讨论 heremap 似乎不适用于承诺。如讨论中所述,我切换到for 循环,它现在正在工作。

async search(ctx) {
    const authors = [
        {
            id: 1,
            name: "author 1"
        },
        {
            id: 2,
            name: "author 2"
        },
    ]

    for (let data of authors) {
        const books = await strapi.query('books').find({ userId: data.id })
        console.log(books)

        // some stuffs here
    }
}

【讨论】:

    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多