Return 对外部函数的承诺,其中包含从内部函数返回的异步数据
Return a promise on an external function with async data returned from an inner function
我正在设计一个用户API,部分API代码如下:
module.exports = {
findByEmail: (email) => {
db.collection('Users').findOne(email: email), (err, result) => {
assert.equal(err, null);
return new Promise(resolve) => {
resolve(result);
}
}
}
}
我在这里的目的是让 findByEmail
return 成为一个承诺,这样它就可以被调用,例如:
require('./models/User').findByEmail({email: 'user@example.com'})
.then((user) => {
console.log('User account', user);
});
但是像上面那样定义我的 API 并没有实现我想要的,因为内部函数是 return 承诺的函数,而外部函数(即 findByEmail
) 最终没有 return 承诺。我如何确保外部函数 return 是使用内部函数 return 编辑的数据的承诺?
当然,让外部函数接受回调是一种选择,但这意味着外部函数不再是可承诺的。
Return 首先是 promise,然后让 promise 回调函数完成剩下的工作。
module.exports = {
findByEmail: (email) => {
return new Promise((resolve, reject) => {
db.collection('Users').findOne(email: email), (err, result) => {
// assert.equal(err, null);
if (err) {
reject(err);
}
resolve(result);
}
}
}
}
我在这里调用了 listings(),其中 jquery ajax 调用是在获得响应后进行的 我将承诺返回给从外部文件调用的函数 getlistings()
function Listings(url){
var deferred = new $.Deferred();
$.ajax({
url: url,
method: 'GET',
contentType: 'application/json',
success: function (response) {
deferred.resolve(response);
},
error: function (response){
deferred.reject(response);
}
});
return deferred.promise();
};
// call from external file
function getListings(){
Listings('/listings.json').then(function(response){
console.log(response);
});
}
我正在设计一个用户API,部分API代码如下:
module.exports = {
findByEmail: (email) => {
db.collection('Users').findOne(email: email), (err, result) => {
assert.equal(err, null);
return new Promise(resolve) => {
resolve(result);
}
}
}
}
我在这里的目的是让 findByEmail
return 成为一个承诺,这样它就可以被调用,例如:
require('./models/User').findByEmail({email: 'user@example.com'})
.then((user) => {
console.log('User account', user);
});
但是像上面那样定义我的 API 并没有实现我想要的,因为内部函数是 return 承诺的函数,而外部函数(即 findByEmail
) 最终没有 return 承诺。我如何确保外部函数 return 是使用内部函数 return 编辑的数据的承诺?
当然,让外部函数接受回调是一种选择,但这意味着外部函数不再是可承诺的。
Return 首先是 promise,然后让 promise 回调函数完成剩下的工作。
module.exports = {
findByEmail: (email) => {
return new Promise((resolve, reject) => {
db.collection('Users').findOne(email: email), (err, result) => {
// assert.equal(err, null);
if (err) {
reject(err);
}
resolve(result);
}
}
}
}
我在这里调用了 listings(),其中 jquery ajax 调用是在获得响应后进行的 我将承诺返回给从外部文件调用的函数 getlistings()
function Listings(url){
var deferred = new $.Deferred();
$.ajax({
url: url,
method: 'GET',
contentType: 'application/json',
success: function (response) {
deferred.resolve(response);
},
error: function (response){
deferred.reject(response);
}
});
return deferred.promise();
};
// call from external file
function getListings(){
Listings('/listings.json').then(function(response){
console.log(response);
});
}