【问题标题】:Issue with async, JS Promise not able to return a result, but works with console.log异步问题,JS Promise 无法返回结果,但适用于 console.log
【发布时间】:2016-09-08 18:39:34
【问题描述】:

目前,当我在运行“node jkl.js”时在“exports.findOneProblem”中使用 console.log(result) 时,它可以工作。我能够看到结果。但是,当我使用 return 而不是 console.log() 时,我得到的只是控制台中的 Promise {pending}。请填补空白....学习如何使用 Promise,谢谢。

 //asd.js

    exports.findOneProblem = function(problemId) {
          return RClient.authenticate(options).then(function (client) {
            const Problem = client.Problem;

            return Problem.findOne(problemId)
          }).then(function(result){
              return result
          });
        };

第二个文件:jkl.js

var okay = require('./asd');

var moneymoney = okay.findOneProblem(263)

console.log(moneymoney)


var honeyhoney = moneymoney.then(function(result){
  return result
})
console.log(honeyhoney)

【问题讨论】:

    标签: javascript node.js asynchronous promise


    【解决方案1】:

    当您收到 Promise 时,这意味着您将在“稍后”获得一个值,即在您的所有同步代码运行完成之后。访问 Promise 提供的值的方法是使用 .then 函数。

    moneymoney.then(function(result) {
      console.log(result);
      // Add your code for using the result of `okay.findOneProblem(263)` here
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      • 2021-10-26
      • 2014-10-02
      • 2014-07-16
      • 2016-04-27
      • 2018-09-01
      相关资源
      最近更新 更多