在“then”链中未定义的返回

yduiuuwa  于 2021-09-23  发布在  Java
关注(0)|答案(3)|浏览(413)

我正在构建一个带有节点和Angular 的应用程序,当我请求这个特定端点时,返回的是一个空数组“[]”。我将return语句放在最后一个'then'块中,但它在前面的for循环之前执行。
如何使此同步,以便在for循环中填充realtemps数组,然后在下一个then语句中返回它?

router.get("", (req, res, next) => {
var templates = [];
var realTemps = [];
const token = req.headers.authorization.split(" ");
const decoded = jwt.verify(token[1], 'secretkey');
decodedFactoryId = decoded.factoryId

Template.findAllByFactoryId(decodedFactoryId)
    .then((results) => {
        for (var i = 0; i < results.length; i++) {
            // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
            for (var j = 0; j < results.length; j++) {
                if (results[i][j].id) {
                    templates.push(results[i][j].id)
                }
            }
        }
    }).then(() => {
        console.log("templates: " + templates)
        for (var i = 0; i < templates.length; i++) {
            console.log(templates[i])
            Template.findByTemplateId(templates[i]).then(result => {
                console.log("here is the result: " + JSON.stringify(result[0]))
                realTemps.push(result);
            })

        }
    })
    .then(() => {
        return realTemps;
    })
 })
qzwqbdag

qzwqbdag1#

简单地做第二个和第三个,然后如下

.then(() => Promise.all(templates.map(template => Template.findByTemplateId(template))))
.then((realTemps) => {
    return realTemps;
})
0g0grzrc

0g0grzrc2#

你应该使用 Promise.all 等待一系列承诺。

Template.findAllByFactoryId(decodedFactoryId)
    .then((results) => {
        for (var i = 0; i < results.length; i++) {
            // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
            for (var j = 0; j < results.length; j++) {
                if (results[i][j].id) {
                    templates.push(results[i][j].id)
                }
            }
        }
    }).then(() => {
      // Promise.all
      return Promise.all(templates.map(template => Template.findByTemplateId(template).then(result => {
        console.log("here is the result: " + JSON.stringify(result[0]))
        realTemps.push(result);
      })))
    })
    .then(() => {
        return realTemps;
    })
 })

为了获得更好的编码体验,我建议您使用 async/await ,这比 .then 声明。

lkaoscv7

lkaoscv73#

你应该使用 Promise.all() 在第二次回调中。

router.get("", (req, res, next) => {
var templates = [];
var realTemps = [];
const token = req.headers.authorization.split(" ");
const decoded = jwt.verify(token[1], 'secretkey');
decodedFactoryId = decoded.factoryId

Template.findAllByFactoryId(decodedFactoryId)
    .then((results) => {
        for (var i = 0; i < results.length; i++) {
            // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
            for (var j = 0; j < results.length; j++) {
                if (results[i][j].id) {
                    templates.push(results[i][j].id)
                }
            }
        }
    }).then(() => Promise.all(templates.map(template => Template.findByTemplateId(template))))

    .then((tmpls) => {
        realTemps =  tmpls;
    })
 })

或使用异步/等待语法:

router.get("", async (req, res, next) => {
  var templates = [];
  var realTemps = [];
  const token = req.headers.authorization.split(" ");
  const decoded = jwt.verify(token[1], 'secretkey');
  decodedFactoryId = decoded.factoryId

  const results = await Template.findAllByFactoryId(decodedFactoryId);

  for (var i = 0; i < results.length; i++) {
    // THIS IS AN AVOIDABLE LOOP, quadratic time must be prevented by correctly formatting the data (TODO)
    for (var j = 0; j < results.length; j++) {
      if (results[i][j].id) {
        templates.push(results[i][j].id)
      }
    }
  }

  realTemps = await Promise.all(templates.map(template => Template.findByTemplateId(template)));
})

相关问题