问题描述
这是我的代码:
检查用户是否关注官方 Twitter 帐户(这里我返回了新的 Promise
var isFollowing = function(sender) {
return new promise(function(resolve, reject) {
var following = false;
var params = {
source_id: sender,
target_screen_name: config.get('twitter.official_account')
};
TwitObj.get('friendships/show', params, function(err, data) {
if (!err) {
following = data.relationship.source.following;
resolve(following);
} else {
reject(err);
}
});
});
};
验证:
var validateMsg = function(dm) {
var sender = getSender(dm);
var result = [];
isFollowing(sender.id)
.then(function(response) {
if (!response) {
result = interactiveMessage(false, lang.__('FOLLOW_MAIN', sender.name));
console.log(result); // Displays as expected
return result; // Not returning value Do I need to return promise again? If yes, WHY?
}
});
};
主要实现:
var direct_message = function(msg) {
verifyAccount().catch(function(err) {
console.error(err);
});
var dm = msg.direct_message;
var result = validateMsg(dm);
console.log(result);
};
问题是我应该如何强制 validateMsg 函数在 then
函数中返回 result
变量.
Questions is how should I force validateMsg function to return result
variable inside then
function.
更新:在调试时,我了解到,console.log(response)
在抛出 undefined 后,验证函数稍后显示then"函数,表示程序无法得到响应由于异步性质,I/O 不会立即被阻塞.如何解决这个问题?
推荐答案
您实际上并未在 validateMsg 函数中返回任何内容.您在 .then
函数中返回一个同步值 ( result
),这是一个单独的函数.
You're not actually returning anything in the validateMsg function. You're returning a synchronous value ( result
) in the .then
function which is a separate function.
要考虑的第二件事是您期待 validateMsg 函数,它是异步的以同步行为.
The second thing to consider is that you're expecting the validateMsg function, which is asynchronous to behave synchronously.
var 结果 = validateMsg(dm);
实现我认为您想要做的事情的方法包括进行以下更改:1)在validateMsg函数中返回promise链.
The way to achieve what I believe you're looking to do involves making the following changes:1) Return the promise chain in the validateMsg function.
var validateMsg = function(dm) {
var sender = getSender(dm);
var result = [];
return isFollowing(sender.id)
.then(function(response) {
if (!response) {
result = interactiveMessage(false, lang.__('FOLLOW_MAIN', sender.name));
return result;
}
// Not sure what you want to do here if there is a response!
// At the moment you're not doing anything if the validation
// is successful!
return response;
});
};
2) 更改您的函数调用,因为您现在要返回一个 promise.
2) Change your function call, since you're now returning a promise.
validateMsg(dm).then( function( result ){
console.log( result );
})
3) 如果只是为了帮助您调试,请考虑在某处添加一个 catch :)
3) Consider adding a catch somewhere if only to help you debug :)
validateMsg(dm).then( function( result ){
console.log( result );
})
.catch( function( err ){
console.log( "Err:::", err );
});
这篇关于蓝鸟承诺返回“未定义"当在“then"里面返回时功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!