Returning a value from a function depending on whe

2019-09-02 06:56发布

问题:

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.
}

I'm using a node module that someone else wrote. It returns a promise. I want to return either a string or a new Error() depending on whether the Promise object returned by the module resolved or not. How can I do this?

I can't return inside the finally() callback either because that return would apply to the callback function not my task function.

回答1:

dbConnection.then().catch() will itself return a promise. With that in mind, we can simply write the code as return dbConnection.then() and have the code that uses the function treat the return value as a promise. For example,

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
}


回答2:

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

This will return a promise which you can then chain.

The point of using promises is similar to using callbacks. You don't want the CPU to sit there waiting for a response.