gpt4 book ai didi

javascript - async/await 不适用于 promisify

转载 作者:行者123 更新时间:2023-11-30 21:05:14 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com