环回异步/等待未处理的承诺拒绝警告问题



在环回 3 中当我在保存之前实现异步/等待操作钩

子时
Entry.observe('before save', async (ctx, next) =>{
    if(ctx.instance.images){
        Entry.upload(ctx.instance.images[0].src).then(data => {
            ctx.instance.image = data;
        });
    }
});

控制台打印此错误

(node:29323) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
(node:29323) 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.

我怎样才能摆脱这个问题!?

无法弄清楚那个承诺在哪里,一旦我删除异步/等待,这条消息就会消失。

您需要为 Entry.upload 承诺指定 .catch。

Entry.upload(ctx.instance.images[0].src).then(data => {
        ctx.instance.image = data;
    }).catch(console.error);

一些旧版本的 NodeJS 可能不会有这个错误。您需要始终使用 catch 作为承诺,否则应用程序将崩溃。

使用try/catch块,并在声明函数(或 Promise 函数(时始终返回已解决或拒绝async承诺

Entry.observe('before save', async (ctx) =>{
    try {
      ctx.instance.image = await Entry.upload(ctx.instance.images[0].src)
    } catch(error){
      return Promise.reject(error)
    }
    return Promise.resolve()
});

相关内容

最新更新