0
async function testSync() {
  var result = await new Promise(function (resolve) {
    test(function (result) {
      resolve(result);
    });
  });
  return result;
}

function test(callback) {
  setTimeout(callback, 1000);
}

async function run() {
  console.log(1);
  var r = await testSync();
  console.log(r)
  console.log(3);
}

run();

I successfully made two functions. One async and one sync, however I am forced to put testSync() in async function.

But running node modules function fs.readfilesync(), for example, I do not have to do that. Can someone explain why and how i can make sync functions, like fs does it?

PragmaticEd
  • 505
  • 1
  • 4
  • 14
  • No, all of your functions can be considered async. Especially the ones defined as `async function`. You make synchronous functions by not doing anything asynchronous in them. A synchronous sleep isn’t possible in the base library and it isn’t a good idea, either. – Ry- Aug 21 '19 at 05:36
  • Possible duplicate of [using await on global scope without async keyword](https://stackoverflow.com/questions/51525234/using-await-on-global-scope-without-async-keyword) - + [some more](https://www.google.com/search?q=node+js+global+async+site:stackoverflow.com) – Lawrence Cherone Aug 21 '19 at 05:37
  • the synchronous `fs` functions in nodejs are likely coded in c/c++ - so, one way to create synchronous functions in nodejs is using node-FFI for example – Jaromanda X Aug 21 '19 at 05:42
  • 1
    If something seems hard, it could be an indicator that it's a bad approach to solving whatever problem you're trying to solve. Can you [state your real problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), assuming this isn't purely out of curiosity? Thanks. – ggorlen Aug 21 '19 at 05:46

1 Answers1

0

Starting with node 8.0.0, you can use this:

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);

async function myF() {
  let names;
  try {
    names = await readdir('path/to/dir');
  } catch (err) {
    console.log(err);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();