【问题标题】:How to Print the Result coming from the Promise Function [duplicate]如何打印来自 Promise 函数的结果 [重复]
【发布时间】:2017-05-18 16:50:33
【问题描述】:

我刚开始学习 Promise,我得到控制台结果为 [ Promise { pending } ] 我想打印来自该函数的确切结果,谁能帮我解决这个问题。

exports.listProjectRepos1 = (req, res)=> {
    let pID = mongoose.Types.ObjectId(req.params.projectId);
    console.log("User Id is ", req.user._id);
    let query = {
        userID: mongoose.Types.ObjectId(req.user._id),
        projectID: pID
    };
        RepositoriesSchema.find(query).lean().then((repos)=> {
            return repos
        }).then((repos)=> {
            let roots = repos.map(exports.populateCodestack1);
            console.log(roots);// trying to Print the Results here
        });
};


exports.populateCodestack1 = function (repo) {
    return new Promise((resolve, reject)=> {
        Promise.all([new Promise((resolve, reject)=> {
            let codeId = repo.codeStack;
            CodeStacksSchema.findOne({ID: codeId}).lean().exec(function (err, codeStack) {
                if (codeStack) {
                    repo.stack = codeStack.name;
                    resolve(repo)
                }
            });
        }),
            new Promise((resolve, reject)=> {
                let owner = mongoose.Types.ObjectId(repo.SCMAccount);
                console.log("Owner Id is", owner);
                ScmaAccount.findOne({_id: owner}).lean().exec(function (err, scm) {
                    if (scm) {
                        repo.type = scm.type;
                        resolve(repo);
                    }
                });
            })

        ]).then(function (result1) {
           // console.log("Refresh Result",result);
            resolve(result1);
        })
    })
};

我想打印函数的输出。

【问题讨论】:

  • 避免使用Promise constructor antipattern!只需return Promise.all(…),不要将其包装在任何东西中。并且不要忘记reject你的承诺,以防出现错误。

标签: javascript node.js promise bluebird q


【解决方案1】:

exports.populateCodestack1 返回一个 Promise,因此roots 将包含一个 Promise 列表。

如果您想等到数组中的所有 Promise 都解决后,您可以将其传递给 Promise.all

RepositoriesSchema.find(query).lean()
  .then( repos => Promise.all(repos.map(exports.populateCodestack1)) )
  .then( roots => {
    console.dir(roots);
  });

除此之外:如果你使用new Promise,那么你应该处理你的错误情况,并且只有在你需要包装一个不支持承诺的函数时才使用new Promise,但永远不要包装一个现有的承诺对象:

exports.populateCodestack1 = function(repo) {
  return Promise.all([
    new Promise((resolve, reject) => {
      let codeId = repo.codeStack;
      CodeStacksSchema.findOne({
        ID: codeId
      }).lean().exec(function(err, codeStack) {
        if (err) {
          reject(err);
        } else {
          repo.stack = codeStack.name;
          resolve(repo)
        }
      });
    }),
    new Promise((resolve, reject) => {
      let owner = mongoose.Types.ObjectId(repo.SCMAccount);
      console.log("Owner Id is", owner);
      ScmaAccount.findOne({
        _id: owner
      }).lean().exec(function(err, scm) {
        if (err) {
          reject(err)
        } else {
          repo.type = scm.type;
          resolve(repo);
        }
      });
    })
  ])
};

编辑

因为 mongoose 库已经支持 Promises,所以应该可以进一步简化它:

exports.populateCodestack1 = function(repo) {
  return Promise.all([
    CodeStacksSchema.findOne({
      ID: repo.codeStack
    }).lean().then(codeStack => {
      repo.stack = codeStack.name;
      return repo
    }),
    ScmaAccount.findOne({
      _id: mongoose.Types.ObjectId(repo.SCMAccount)
    }).lean().then(scm => {
      repo.type = scm.type;
      resolve(repo);
    })
  ])
};

【讨论】:

  • .then((repos) => { return repos }) 是多余的。
  • @DanielB 是的,一开始我没看到,代码有点乱。
  • @DanielB 你能解释一下它是如何多余的......我只是说学习。你能解释一下吗?
  • @Jeevan 查看您的代码RepositoriesSchema.find(query).lean().then((repos)=> { return repos }).then((repos),很明显.lean()repos 对象返回给以下.then()。所以问问为什么你应该在中间有第二个.then(),它只返回repos。这就像写一个函数function(x) { return x; }
猜你喜欢
  • 1970-01-01
  • 2021-09-30
  • 2021-11-09
  • 2016-11-22
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多