You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将dynogels回调转为Promise?能否用Promise.resolve()作回调?

Converting dynogels' Callback-based 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:34:12