我尝试用Promise Asynchronous调用我用NAN(Node.js的本地抽象)实现的本地C ++函数。不幸的是,承诺从未解决。 我的Java代码。
function callbackDoAsyncStuffFirst() {
return new Promise(function (resolve, reject) {
module.doAsyncStuffFirst(function (error, a, v, b) {
if (error) {
return reject(error);
}
console.log("Resolve First: ", a, " ", b, " ", v, " ");
let ret = [a, b, v];
console.log("Return frist Resolve");
return resolve(ret);
});
});
}
function callbackDoAsyncStuff() {
return new Promise(function (resolve, reject) {
module.doAsyncStuffSecond(function (error, a, b) {
if (error) {
return reject(error);
}
console.log("Returned: ", a, " ", b);
let ret = [a, b];
console.log("Call Second Resolve");
return resolve(ret);
}, 'valueA', 'valueB');
});
}
let p = callbackDoAsyncStuffFirst().then((retArray) => { console.log("resolve first-->", retArray) });
let second = callbackDoAsyncStuff().then((retArray) => { console.log("resolve second-->: ", retArray) });
控制台输出看起来像
C++: Start Execute
C++: HandleOKCallback
JS: Resolve First: a, b, v
JS: Return frist Resolve
此后,什么也没有发生。
答案 0 :(得分:0)
这个伪造的模块表明问题出在您的C ++插件中,而不是您的JavaScript中,该问题在这里可以正常工作。
它还演示了如何使用一组“成功的”参数来调用回调,因为您将第一个回调参数解释为错误,该参数必须为false才能使您不拒绝诺言。
var module = {
doAsyncStuffFirst: (cb) => {
cb(undefined, 'dummy_a1', 'dummy_v1', 'dummy_b1');
},
doAsyncStuffSecond: (cb) => {
cb(undefined, 'dummy_a2', 'dummy_b2');
}
}
function callbackDoAsyncStuffFirst() {
return new Promise(function (resolve, reject) {
module.doAsyncStuffFirst(function (error, a, v, b) {
if (error) {
return reject(error);
}
console.log("Resolve First: ", a, " ", b, " ", v, " ");
let ret = [a, b, v];
console.log("Return frist Resolve");
return resolve(ret);
});
});
}
function callbackDoAsyncStuff() {
return new Promise(function (resolve, reject) {
module.doAsyncStuffSecond(function (error, a, b) {
if (error) {
return reject(error);
}
console.log("Returned: ", a, " ", b);
let ret = [a, b];
console.log("Call Second Resolve");
return resolve(ret);
}, 'valueA', 'valueB');
});
}
let p = callbackDoAsyncStuffFirst().then((retArray) => { console.log("resolve first-->", retArray) });
let second = callbackDoAsyncStuff().then((retArray) => { console.log("resolve second-->: ", retArray) });