根据是否解析了 Promise 从函数返回值

Returning a value from a function depending on whether a Promise was resolved or not

本文关键字:Promise 函数 返回值 是否      更新时间:2023-09-26
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函数。

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
}
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 坐在那里等待响应。