我一直在寻找这个问题的答案,因为我确信以前肯定有人问过这个问题,但我似乎找不到一个对我来说有意义的答案。
在节点中,我正在创建几个 Firebase“观察者”,它们负责对 Firebase 中的数据进行一些清理,并在参数状态发生变化时发送短信。在下面的代码中,我有一个 startChildChangedWatcher
和一个 sendSMS
函数。当我尝试从 bitly.shorten()
中的 Promise 调用 sendSMS
时,就会出现问题。它永远不会被执行,尽管在 promise 之外调用时它工作得很好。我尝试定义 var self = this;
因为我认为它与范围有关,然后调用 self.sendSMS("")
,但没有运气。此外,仅调用 Promise 内的两个日志语句之一。我确信这非常简单,但有时在寻找类似答案时很难知道到底要搜索什么。
ref.authWithCustomToken(token, function(error, authData){
if (error) {
console.log(error);
} else {
console.log("Login successful");
startChildChangedWatcher();
...
}
});
var startChildChangedWatcher = function() {
deliveriesRef.on('child_changed', function(snapshot) {
console.log(snapshot.val());
if (snapshot.val().completed === true) {
if (snapshot.val().urlToShorten !== undefined) {
console.log("Image url found, proceeding to shorten url");
bitly.shorten(snapshot.val().urlToShorten)
.then(function(response) {
var shortUrl = response.data.url;
//This prints fine
console.log('URL Received, sending SMS');
sendSMS("Your url is: " + shortUrl);
//This never prints
console.log("Url shortened, proceeding to send sms");
}, function(err){
console.log(err)
});
} else {
...
}
}
});
};
var sendSMS = function(message) {
console.log(message);
twilio.sendMessage({
to: +447564908855,
from: +441241797052,
body: message
}, function(err, responseData) {
if (err) {
console.log("Error sending message: " + err);
} else {
console.log("Message sent. Response: " + responseData);
}
});
};
最佳答案
我认为您没有在代码中定义 url。
sendSMS("您的网址是:"+ url);
到
sendSMS("您的网址是:"+ ShortUrl);
ref.authWithCustomToken(token, function(error, authData){
if (error) {
console.log(error);
} else {
console.log("Login successful");
startChildChangedWatcher();
...
}
});
var startChildChangedWatcher = function() {
deliveriesRef.on('child_changed', function(snapshot) {
console.log(snapshot.val());
if (snapshot.val().completed === true) {
if (snapshot.val().urlToShorten !== undefined) {
console.log("Image url found, proceeding to shorten url");
bitly.shorten(snapshot.val().urlToShorten)
.then(function(response) {
var shortUrl = response.data.url;
//This prints fine
console.log('URL Received, sending SMS');
sendSMS("Your url is: " + url);
//This never prints
console.log("Url shortened, proceeding to send sms");
}, function(err){
console.log(err)
});
} else {
...
}
}
});
};
var sendSMS = function(message) {
console.log(message);
twilio.sendMessage({
to: +447564908855,
from: +441241797052,
body: message
}, function(err, responseData) {
if (err) {
console.log("Error sending message: " + err);
} else {
console.log("Message sent. Response: " + responseData);
}
});
};
关于javascript - 函数未在 Promise 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836502/