我正在使用q package将我的js代码从异步转换为同步。 我不知道我的理解是否正确。 我写了下面的代码段
var Q = require('q')
function onMessage() {
console.log("Before calling Q.fncall");
Q.fcall(processMessage)
.then(function () {
console.log("processMessage execution compleated");
})
.done();
console.log("Calling Q.fncall Compleated");
return true;
}
function processMessage() {
var defer = Q.defer();
console.log("processMessage Entered");
setTimeout(function () {
console.log("processMessage processed");
defer.resolve();
console.log("processMessage defer Resolved");
}, 10)
console.log("ProcessMessage Before Exit");
return defer.promise;
}
onMessage()
代码的输出为::::
Before calling Q.fncall
Calling Q.fncall Compleated
processMessage Entered
ProcessMessage Before Exit
processMessage processed
processMessage defer Resolved
processMessage execution compleated
但是我的期望是得到::::
Before calling Q.fncall
processMessage Entered
ProcessMessage Before Exit
processMessage processed
processMessage defer Resolved
processMessage execution compleated
Calling Q.fncall Compleated
有什么我想念的东西吗?怎么能实现?...
答案 0 :(得分:0)
这应该解决
var Q = require('q')
function onMessage() {
console.log("Before calling Q.fncall");
return new Promise(resolve => {
Q.fcall(processMessage)
.then(function () {
console.log("processMessage execution compleated");
console.log("Calling Q.fncall Compleated");
})
.done(() => resolve(true));
})
}
function processMessage() {
var defer = Q.defer();
console.log("processMessage Entered");
setTimeout(function () {
console.log("processMessage processed");
defer.resolve();
console.log("processMessage defer Resolved");
}, 10)
console.log("ProcessMessage Before Exit");
return defer.promise;
}
onMessage();