如何将dynogels回调转为Promise?能否用Promise.resolve()作回调?
destroy to Promises Got it, let's sort this out for you! The problem with passing Promise.resolve() as a callback is that dynogels expects a standard error-first callback function (the classic function(err) { ... } format), not a Promise object directly. That approach won't work because dynogels will try to invoke whatever you pass as a callback—and a Promise isn't a callable function.
Here are two reliable ways to convert this callback method to use Promises:
1. Use Node.js' util.promisify (Simplest Approach)
Node.js has a built-in utility to convert callback-style functions to Promise-based ones, which is perfect here:
const util = require('util'); // Convert the destroy method to return a Promise const destroyBlogPost = util.promisify(BlogPost.destroy); // Now use it with Promise/then syntax destroyBlogPost('foo@example.com', 'Hello World!') .then(() => { console.log('post deleted'); }) .catch(err => { console.error('Failed to delete post:', err); });
If you're using Node.js 14+, you can even use async/await for cleaner code:
const util = require('util'); const destroyBlogPost = util.promisify(BlogPost.destroy); async function deletePost() { try { await destroyBlogPost('foo@example.com', 'Hello World!'); console.log('post deleted'); } catch (err) { console.error('Deletion error:', err); } } deletePost();
2. Manual Promise Wrapping (For Full Control)
If you want to understand the underlying mechanics, you can wrap the destroy call in a Promise manually:
function destroyBlogPost(hashKey, rangeKey) { return new Promise((resolve, reject) => { BlogPost.destroy(hashKey, rangeKey, (err) => { if (err) { // Reject the Promise if there's an error reject(err); } else { // Resolve the Promise when deletion succeeds resolve(); } }); }); } // Usage is the same as above destroyBlogPost('foo@example.com', 'Hello World!') .then(() => console.log('post deleted')) .catch(err => console.error('Error:', err));
Why Your Original Attempt Didn't Work
Promise.resolve() returns a resolved Promise instance, not a function. When dynogels tries to run your "callback" with callback(err), it's trying to invoke a Promise object—which throws an error because Promises aren't callable. You need to pass a function that handles the error and resolves/rejects a Promise accordingly.
内容的提问来源于stack exchange,提问作者ckky1213

