I try to call my native C++ function implemented with NAN(Native Abstraction for Node.js) with a Promise Asynchronous. Unfortunately the Promise is never resolved. My Code in Javascript.
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) });
The console output looks like
C++: Start Execute
C++: HandleOKCallback
JS: Resolve First: a, b, v
JS: Return frist Resolve
After this nothing happens any more.
This fake module demonstrates that the problem is in your C++ plugin, not in your JavaScript, which works correctly here.
It also demonstrates how to call the callback with a "successful" set of arguments, in that the first callback argument you are interpreting as an error, which must be falsey in order for you not to reject your promise.
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) });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.