'then' 链中未定义 return

Undefined return in a 'then' chain

我正在构建一个带有节点和 angular 的应用程序,当我请求这个特定端点时,我得到 returned 一个空数组“[]”。我将 return 语句放在最后的 'then' 块中,但这会在之前的 for 循环之前执行。

我怎样才能使这个同步,以便在 for 循环中填充 realTemps 数组,然后在下一个 then 语句中 returned?

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;
    })
 })

您应该使用 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语句更清晰。

您应该在第二个回调中使用 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;
    })
 })

或使用async/await语法:

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)));
})

简单的制作第二个和第三个.然后如下

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