【问题标题】:Capture the solution of Promise.all() in Javascript在 Javascript 中捕获 Promise.all() 的解决方案
【发布时间】:2020-10-03 14:04:39
【问题描述】:

我正在使用数组的值作为参数进行猫鼬查询。 所以我需要做很多查询。而且我想将它们保存在一个对象中,以便以后在同一个函数中使用它。

但是,下面的代码只打印“[undefined]”。但是,我知道第一个查询返回一个值,因为我之前单独测试过,所以返回的带有 undefined 的数组是错误的。 我什至无法想象我现在做错了什么。

 async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await Promise.all(valores.map(async valor => {
                const query = model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}}) //Everything working here

            }))

            console.log(documentos) //Prints " [undefined] "       
 }

【问题讨论】:

  • Promise.all 中的承诺不返回任何内容。您只需创建一个变量,仅此而已 - 它不再使用。您可能只需要 return model.find({url: {'$in': [new RegExp(.*${valor}.*, 'i')]}}) 而不是声明变量。
  • 如所写,地图回调不返回任何内容;它需要返回 Promise。 query 不是 Promise 但 query.exec() 返回 Promise,因此你需要写 return model.find(.....).exec();
  • valores.map(...) 将因此返回一个承诺数组,这正是Promise.all() 所需要的。如果所有查询都成功,documentos 将包含查询结果。如果任何一个查询失败,整个Promise.all() 将失败,因此您需要一个try{} catch(error){} 结构来捕获和处理错误的可能性。
  • “我如何在 .then() 链中访问之前的承诺结果?”的副本- 胡言乱语!
  • 你只需要在箭头函数内返回

标签: javascript mongoose promise async-await


【解决方案1】:

尝试在 map 内的异步函数中返回查询。

 async function buscarNoBdPorValorContido(model, atributo, valor, resposta){
        var documentos = []
        var valores = valor.split(` `)
        documentos = await Promise.all(valores.map(async valor => {
                return model.find({url: {'$in': [new RegExp(`.*${valor}.*`, 'i')]}}) //Everything working here

            }))

            console.log(documentos) //Prints " [undefined] "       
 }

【讨论】:

    【解决方案2】:

    我已经这样解决了:

     async buscarNoBdPorValorContido(model, atributo, valor){
            var valores = valor.split(` `)
            var documentos = valores.map(value => {
                const query = model.find({url: {'$in': [new RegExp(`.*${value}.*`, 'i')]}})
                return query.exec() 
            })
            var resultados = await Promise.all(documentos)
            return resultados  
    
        },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多