根据是否解析了 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 对象是否解析。我该怎么做?
我也无法在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 坐在那里等待响应。
相关文章:
- 根据是否解析了 Promise 从函数返回值
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- AngularJS和promise值在调用本地函数时的效果-未定义
- Promise函数在.then之后未运行函数化
- 如何在异步函数中正确使用Promise.all()和then()
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- 多次调用promise函数,直到另一个promise函数满足条件
- 在循环中调用Bluebird Promise函数
- 如何在循环中调用Promise函数并保存其返回值
- Nodejs 没有异步执行 promise 函数
- NodeJS - 创建一个使用 Sequelize 函数的 Promise 函数
- 如何返回以下 _.map + Promise 函数
- 访问Node.js中其他promise函数中的firebase防火promise局部变量-避免全局
- 在另一个函数中调用promise函数时出错
- 在Nodejs中编写promise函数时,undefined不是函数
- 在AngularJS中创建一个Q promise函数调用阻塞
- 从angular的promise函数中获取数据
- jQuery递归的Promise函数有什么问题?
- Bluebird Promise:在新的Promise(函数(resolve,reject)中可以有多个reject()
- 在Angular 2中,如何从一个Promise函数调用另一个Promise函数