javascript - async/await 不适用于 promisify

标签 javascript node.js asynchronous es6-promise

我正在尝试使用 util.promisify功能,但我的代码不起作用。我想我不明白 promises/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;
};

Async/await 不起作用,我得到:

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.

最佳答案

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

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));

关于javascript - async/await 不适用于 promisify,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46716759/

相关文章:

javascript - Cordova 键盘插件 native.keyboardopen 事件未触发。如何在键盘打开时停止滚动

javascript - 使用 YepNope/Modernizr 加载外部 Google 字体样式表

javascript - 从模块的原型(prototype)方法返回值,同步还是异步?

javascript - 我正在尝试使用传单 javascript 库可视化 map 上的一些数据点。你能告诉我我的代码有什么问题吗?

javascript - 类型错误:无法读取未定义的 React 属性 'any'

javascript - 如何根据屏幕宽度/高度在 <body> 中居中 <svg>

node.js - 意外的 Node.js 程序流程

node.js - 创建一个接受参数的 expressjs 中间件

node.js - 来自图形魔法的缩略图,没有放大

javascript - 网站有哪些好的 JavaScript/AJAX 界面模式?