gpt4 book ai didi

javascript - 在执行后续步骤之前返回异步的 Sequelize 结果

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:22 25 4
gpt4 key购买 nike

我的函数可以执行所有逻辑,然后我想获取所有产品的计数。我可以执行 .then() 但我不希望它嵌套。我也想先运行这个查询。我怎样才能运行它并首先在变量中获取结果。我尝试了异步等待,但在完成之前它仍然跳到下一部分。

我也尝试过 Promise.resolve

// initial code here 

let productCount = Promise.resolve( Product.count({
where: {
title: {
$like: '%'+searchTerm+'%'
},
},
}).then(result => {
return result
})

)

// get product count
// do some logic

// my next query which I do results in .then

最佳答案

我不确定我是否完全理解了您的意思,但如果您只想等待 Product.count() 完成后再继续,那么您可以执行以下操作:

async function productCount(searchTerm) {
let productCount = await Product.count({
where: {
title: {
$like: '%'+searchTerm+'%'
},
},
})
return productCount
}

当您调用productCount()时,您还必须使用await并将“async”放在调用函数的名称前面,例如:

async function callingFunction() {
...
let productCount = await productCount(searchTerm)
// do something with productCount
}

关于javascript - 在执行后续步骤之前返回异步的 Sequelize 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com