在我的服务器应用程序中,我有一些方法,如:
insertUserJoinedMessageAndSendMessage
)getOwnerPhoneNumberUniqueIds
)在这个解决方案中我有:
insertUserJoinedMessageAndSendMessage(userPhoneNumbers, assignedUserId.id)
.then(function (t) {
return getOwnerPhoneNumberUniqueIds(userPhoneNumbers);
})
.then(function (result) {
log.info(result);
})
.catch(function (error) {
log.info(error);
});
方法,insertUserJoinedMessageAndSendMessage
方法正常工作没有任何问题,我想从getUserId()
Promise函数获取嵌套Promise的生成数据为getOwnerPhoneNumberUniqueIds()
,但我无法在此打印数据代码的一部分为log.info(result);
,因为我无法从getOwnerPhoneNumberUniqueIds()
function insertUserJoinedMessageAndSendMessage(userPhoneNumbers, ownerUserId) {
return new Promise(function (resolve, reject) {
let query = "INSERT INTO `userJoinedMobileNumbers` (`id`, `userId`, `nameAndFamily`, `mobileNumber`, `created_at`, `updated_at`) VALUES ";
userPhoneNumbers.map(function (curr) {
query += "(NULL, " + ownerUserId + ", " + curr.contactName + ", " + curr.contactPhone + ", CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),";
});
query = query.substr(0, query.length - 1) + ";";
connection.query(query, function (err, results) {
if (err) return reject(err);
resolve(true);
});
});
}
function getOwnerPhoneNumberUniqueIds(data) {
return Promise.all(data.map(function (curr) {
return getUserId(curr.contactPhone)
.then(function (data) {
log.info("1) " + data);
return {id: data};
});
})).then(function (accountNumbers) {
log.info("2) " + accountNumbers);
return accountNumbers
}).catch(function (err) {
console.log(err);
});
}
function getUserId(contactPhone) {
return new Promise(function (resolve, reject) {
var query = "SELECT id FROM sendMessageUserJoined WHERE `phoneNumber` ='" + contactPhone + "'";
connection.query(query, function (err, results) {
if (err) return reject(err);
if (results.length > 0) {
log.info("0) " + results[0].id);
resolve(results[0].id);
}
});
});
}
在log.info("0) " + results[0].id);
中我获得sql命令的结果并且返回id
成功到getOwnerPhoneNumberUniqueIds()
并且我可以打印结果,这部分代码为log.info("1) " + data);
,现在怎么能我把它归还:
.then(function (accountNumbers) {
log.info("2) " + accountNumbers);
return accountNumbers
})
log.info("2) " + accountNumbers);
不要打印return {id: data};
答案 0 :(得分:1)
问题出在getUserId
。
在某些情况下,您无法解决或拒绝承诺。因此,您的Promise.all
返回的承诺保持待定状态。
function getUserId(contactPhone) {
return new Promise(function (resolve, reject) {
var query = "SELECT id FROM sendMessageUserJoined WHERE `phoneNumber` ='" + contactPhone + "'";
connection.query(query, function (err, results) {
if (err) return reject(err);
if (results.length > 0) {
log.info("0) " + results[0].id);
resolve(results[0].id);
}
else { //this part is missing
resolve(); //or reject
}
});
});
}