NodeJS set time out for an API call

https://stackoverflow.com/questions/63248292/how-to-set-a-time-limit-to-a-method-in-nodejs

Following code snippet demonstrates the usage of timeout function written above. It mocks a api request that returns a response after 4 seconds.

function timeout(seconds) {
  return new Promise(resolve => {
    setTimeout(resolve, seconds * 1000);
  });
}

function apiRequest() {
  return new Promise(resolve => {
    setTimeout(() => resolve('Hello World'), 4000);
  });
}

let test = async () => {
  let externalCallResponse = '';

  setTimeout(async () => {
    externalCallResponse = await apiRequest();
  }, 0);

  await timeout(3); // wait for 3 seconds

  if (externalCallResponse != '') return true;
  else return false;
};

test()
  .then(res => console.log(res))
  .catch(err => console.log(err.message));