【问题标题】:Returning a value from a function depending on whether a Promise was resolved or not根据 Promise 是否已解决从函数返回值
【发布时间】:2016-09-12 13:52:38
【问题描述】:
const dbConnection = require("../dbConnection");    

var task = function () {
    var response = "";
    dbConnection.then(function () {
        //do something here
        response = "some value";            
    })
    .catch(function () {
       response = new Error("could not connect to DB");
    });

    //I can't return response here because the promise is not yet resolved/rejected.
}

我正在使用其他人编写的节点模块。它返回一个承诺。我想返回一个字符串或new Error(),具体取决于模块返回的 Promise 对象是否已解析。我该怎么做?

我也无法在 finally() 回调中返回,因为 return 将应用于回调函数而不是我的 task 函数。

【问题讨论】:

  • 为什么不能按原样使用模块?

标签: javascript node.js asynchronous promise


【解决方案1】:
const dbConnection = require("../dbConnection");    

var task = function () {
  var response = "";
  return dbConnection.then(function () {
    //do something here
    response = "some value";
    return response;
  })
  .catch(function () {
   response = new Error("could not connect to DB");
   return response;
  });
}

这将返回一个你可以链接的承诺。

使用 Promise 的意义类似于使用回调。您不希望 CPU 坐在那里等待响应。

【讨论】:

    【解决方案2】:

    dbConnection.then().catch() 本身会返回一个承诺。考虑到这一点,我们可以简单地将代码编写为return dbConnection.then(),并让使用该函数的代码将返回值视为一个承诺。例如,

    var task = function () {
      return dbConnection.then(function() {
        return "Good thing!"
      }).catch(function() {
        return new Error("Bad thing.")
      })
    }
    
    task().then(function(result){
      // Operate on the result
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 2016-10-03
      • 2017-10-24
      • 2016-12-28
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 2021-12-29
      • 2021-12-15
      相关资源
      最近更新 更多