How to use the promisify function from es6-promisify

Find comprehensive JavaScript es6-promisify.promisify code examples handpicked from public code repositorys.

es6-promisify.promisify is a function that converts callback-style functions into Promise-based functions.

157
158
159
160
161
162
163
164
165
166
async Once(root) {
  const resolver = ResolverFactory.createResolver({
    fileSystem,
    ...resolveOptions,
  });
  const resolve = promisify(resolver.resolve.bind(resolver));
  const readFile = promisify(fileSystem.readFile.bind(fileSystem));

  let preprocessPlugins = [];
  if (preprocessValues) {
fork icon8
star icon20
watch icon1

+ 5 other calls in file

68
69
70
71
72
73
74
75
76
77
78
79
    next()
})


// promisify some callback based APIs
app.use((req, res, next) => {
    req.login = promisify(req.login, req)
    next()
})


const multerOptions = multer.diskStorage({
fork icon0
star icon1
watch icon0

How does es6-promisify.promisify work?

es6-promisify.promisify is a function that takes a Node.js-style callback-based function and returns a new function that returns a promise. When the new function is called, it will call the original function and resolve or reject the promise based on whether the original function's callback was called with an error or a value.

63
64
65
66
67
68
69
70
71
72
73
const _resetTestQueryLog = () => (queryLog = []);
const ESCAPE_SYMBOL = Symbol("ESCAPED");


const initConnection = newConnection => {
  transactionStack = [];
  promisifiedQueryFunction = promisify(newConnection.query.bind(newConnection));
  promisifiedStartTransaction = promisify(
    newConnection.beginTransaction.bind(newConnection)
  );
  promisifedCommitTransaction = promisify(
fork icon0
star icon0
watch icon0

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
const { promisify } = require("es6-promisify");
const fs = require("fs");

const readFileAsync = promisify(fs.readFile);

readFileAsync("example.txt", "utf8")
  .then((data) => console.log(data))
  .catch((err) => console.error(err));

In this example, promisify is used to create a promise-based version of the fs.readFile function, which traditionally takes a callback as its last argument. The resulting readFileAsync function can then be called with the same arguments as fs.readFile, but returns a promise that resolves with the file contents as a string.