从函数返回值,具体取决于是否已解决Promise [英] Returning a value from a function depending on whether a Promise was resolved or not
问题描述
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对象是否已解析.我该怎么办?
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?
我也不能在 finally()
回调内部返回,因为 return
会应用于回调函数,而不是我的 task
函数.
I can't return inside the finally()
callback either because that return
would apply to the callback function not my task
function.
推荐答案
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.
使用promise的要点类似于使用回调.您不希望CPU坐在那里等待响应.
The point of using promises is similar to using callbacks. You don't want the CPU to sit there waiting for a response.
这篇关于从函数返回值,具体取决于是否已解决Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!