我正在尝试使用util.promisify函数,但我的代码不起作用。我想我不明白承诺/宣传是如何运作的。如果我使用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.
Async / await不起作用,我得到:
Entity1
答案 0 :(得分:1)
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));
TestServer1
ping TestServer1 - success
telnet TestServer1 1433 - failed
答案 1 :(得分:0)
您的测试函数必须是Async,并且您只需要在promisify(embeded)上使用Await。请注意,您需要在异步函数内使用getAllInterests,在这种情况下,我将其放在异步闭包内。 (我自己测试了代码,并且性能良好)。而且调试和维护也更灵活。
const oembed = require('oembed-auto');
const { promisify } = require('util');
const test = async () => {
return await promisify(oembed)("http://www.youtube.com/watch?v=9bZkp7q19f0");
}
const getAllInterests = async () => {
const data = await test();
console.log(data);
return data;
};
(async ()=> {
await getAllInterests();
})();