Node-API napi_make_callback behaviour with async JS function handlers

147 Views Asked by At

In my application, I am using Node-API, napi_make_callback to invoke a javascript function which returns some key connecting to different server. The javascript callback function shall perform an socket I/O to get the result from server.

How does the N-API call napi_make_callback be made to wait till the JS async function is complete. I cant make getKey as synchronous function as it involves a I/O

high level example given below. The result.key is not valid.

async function getKey() {
  let obj;
  const endpoint = `https://ip/getKey`;
  const requestParams = {
    client_id: clientId,
  };
  await request.post({ url: endpoint, form: requestParams }, (err, response, body) => {
    if (err) {
      console.log('Error in getting key ');
    }
    else {
      const parsedBody = JSON.parse(body);
      obj.key = parsedBody.key;
    }
  });
  return obj;
}


...
napi_make_callback(env, NULL, recv, getKey, 1, &arg1, &result);
print result.key // gives null . expected a valid key
...
0

There are 0 best solutions below