我正在尝试使用util.promisify函数,但是我的代码无法正常工作。我想我不明白诺言/承诺如何运作。如果使用new Promise,则我的代码有效,但是,如果使用promisify,则无效。

如果我运行此代码:

const oembed = require('oembed-auto');
const { promisify } = require('util');

const test = () => {
  return new Promise((resolve, reject) => {
    oembed("http://www.youtube.com/watch?v=9bZkp7q19f0", function (err, data) {
      resolve(data);
    });
  });
};

module.exports.getAllInterests = async () => {
  const data = await test();
  console.log(data);
  return data;
};


我得到了预期的结果:

{ html: '<iframe width="480" height="270" src="https://www.youtube.com/embed/9bZkp7q19f0?feature=oembed" frameborder="0" allowfullscreen></iframe>',
  author_url: 'https://www.youtube.com/user/officialpsy',
  thumbnail_url: 'https://i.ytimg.com/vi/9bZkp7q19f0/hqdefault.jpg',
  width: 480,
  height: 270,
  author_name: 'officialpsy',
  thumbnail_height: 360,
  title: 'PSY - GANGNAM STYLE(강남스타일) M/V',
  version: '1.0',
  provider_url: 'https://www.youtube.com/',
  thumbnail_width: 480,
  type: 'video',
  provider_name: 'YouTube' }


如果我运行此代码:

const oembed = require('oembed-auto');
const { promisify } = require('util');

const test = () => {
  promisify(oembed)("http://www.youtube.com/watch?v=9bZkp7q19f0").then((data) => {
    resolve(data);
  });
};

module.exports.getAllInterests = async () => {
  const data = await test();
  console.log(data);
  return data;
};


异步/等待不起作用,我得到:

undefined
(node:66423) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: resolve is not defined
(node:66423) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

最佳答案

return中没有test的值,resolve中的undefined.then()

const test = () => promisify(oembed)("http://www.youtube.com/watch?v=9bZkp7q19f0");




module.exports.getAllInterests = async () => {
  let data;
  try {
    data = await test();
    console.log(data);
  } catch (err) {
    console.error(err);
    throw err;
  }
  return data;
};




getAllInterests().then(res => console.log(res), err => console.err(err));

07-24 09:39