最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - node callback to promise with asyncawait - Stack Overflow

programmeradmin4浏览0评论

I'm trying to write a simple function that converts node-style callback functions to promises, so I can use them with async/await.

Current code:

function toPromise(ctx, func, ...args) {
  let newPromise;

  args.push((err, res) => {
    newPromise = new Promise((resolve, reject)=> {
       if(err) reject(err);
       else{
        resolve(res) 
      };
     });
    });

   func.apply(ctx, args);

   return newPromise;
}

example usage:

const match = await toPromise(user, userparePassword, password);
//trying to avoid the following:
userparePassword(password, (err, res) => {
     ... });

This probably doesn't make any sense with some great libraries out there, but I'm just trying to code this as an exercise.

Problem is of course match evaluates to undefined, and apparently the promise gets resolved after the await syntax line.

Any idea how I can resolve this issue?

I'm trying to write a simple function that converts node-style callback functions to promises, so I can use them with async/await.

Current code:

function toPromise(ctx, func, ...args) {
  let newPromise;

  args.push((err, res) => {
    newPromise = new Promise((resolve, reject)=> {
       if(err) reject(err);
       else{
        resolve(res) 
      };
     });
    });

   func.apply(ctx, args);

   return newPromise;
}

example usage:

const match = await toPromise(user, user.parePassword, password);
//trying to avoid the following:
user.parePassword(password, (err, res) => {
     ... });

This probably doesn't make any sense with some great libraries out there, but I'm just trying to code this as an exercise.

Problem is of course match evaluates to undefined, and apparently the promise gets resolved after the await syntax line.

Any idea how I can resolve this issue?

Share Improve this question asked Nov 2, 2015 at 11:47 SenecaSeneca 2,4122 gold badges21 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

Since node v8.0.0 they added util.promisify.

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

const stat = util.promisify(fs.stat);
stat('.').then((stats) => {
  // Do something with `stats`
}).catch((error) => {
  // Handle the error.
});

Ref: https://nodejs/api/util.html#util_util_promisify_original

Your problem is that you are constructing the newPromise inside of the asynchronous callback. So you've still got undefined when you return it. Instead, you will need to call the Promise constructor immediately, and only put the resolve/reject in the asynchronous callback:

function toPromise(ctx, func, ...args) {
    return new Promise((resolve, reject) => {
        args.push((err, res) => {
            if (err) reject(err);
            else resolve(res);
        });
        func.apply(ctx, args);
    });
}

See also How do I convert an existing callback API to promises?

发布评论

评论列表(0)

  1. 暂无评论