question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to use promises for results instead of callbacks?

See original GitHub issue

I’m trying to use ES7 async/await but this library uses callbacks. How can I transform this into a promise?

    this.db.findOne({
      property: 'abc'
    }, function(err, doc) {
    });

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:7

github_iconTop GitHub Comments

22reactions
dschisslercommented, Oct 12, 2015

I found the answer:

function findOne(db, opt) {
  return new Promise(function(resolve, reject) {
    db.findOne(opt, function(err, doc) {
      if (err) {
        reject(err)
      } else {
        resolve(doc)
      }
    })
  })
}
findOne(this.db, {
  abc: 123
}).then(function(doc) {
});
6reactions
dschisslercommented, Oct 12, 2015

Or with async/await:

doc = await findOne(this.db, {
  abc: 123
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using promises - JavaScript - MDN Web Docs
Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.
Read more >
Aren't promises just callbacks? - Stack Overflow
Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you...
Read more >
How to make a Promise out of a Callback function in JavaScript
Callback Hell · Solution 1 (easy): Use Node's “util” module · Solution 2 (involved): Turn the Callback into a Promise.
Read more >
Understanding the Event Loop, Callbacks, Promises, and ...
A promise represents the completion of an asynchronous function. It is an object that might return a value in the future. It accomplishes...
Read more >
Converting Callbacks to Promises in Node.js - Stack Abuse
Let's talk about how to covert callbacks to promises if the util.promisify() function is not available. The idea is to create a new...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found