【发布时间】:2018-03-24 19:31:19
【问题描述】:
我正在尝试使用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;
};
异步/等待不起作用,我得到:
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.
【问题讨论】:
-
我的意思是...
resolve在第二种情况下是未定义的。否则它为什么会给你一个错误说明 -
@KevinB 如果我把它改成
return,结果是undefined,没有错误信息resolve is not defined -
这两个问题不相关。
-
我的意思是,这不是very well documented 或任何东西。 /s 文档中的示例甚至直接按照你需要的代码逻辑。
标签: javascript node.js asynchronous es6-promise