Pg-promise : 空承诺

Pg-promise : Empty promise

我目前正在使用 pg-promise 和 Bluebird 开发一个生成器:

function * getOrRegisterCurrentFriendIfProvided(t)

那应该 return 要么是一个空洞的承诺(如果 t.ctx.context 未定义)
注意:纯蓝鸟中的一个例子:

yield new Promise(function (resolve) { resolve({}) });

或调用另一个函数(提供结果):

yield t.task.call(params.friend,anotherFunction);

有什么方法可以用 pg-promise 表达我的空 Promise(不使用像 t.none("BYPASS QUERY") 这样的查询)?

使用下面的示例,当我这样做时:

db.task(getOrRegisterCurrentFriendIfProvided)
   .then(function(result){
        console.log(result) // gives me undefined
   })

我没有定义。我确信 t.ctx.context 未定义

时会出现问题

编辑:完整代码:

function * getOrRegisterCurrentFriendIfProvided(t) {
let params = t.ctx.context;

if (params.hasOwnProperty("friend")) {
    yield t.task.call(params.friend,anotherFunction);
} else {
    // returns a empty result ( {} )  promise , just to make promise chain not angry
    yield new Promise(function (resolve) { resolve({}) });
}

}

您从任务中获得 undefined 的原因是您的回调未返回任何内容。将其更改为以下内容:

function * getOrRegisterCurrentFriendIfProvided(t) {
    let params = t.ctx.context;
    if (params.hasOwnProperty("friend")) {
        return yield t.task.call(params.friend, anotherFunction);
    }
}

我还删除了 else 部分,因为它在那里没有用,因为您使用它的方式,即不返回任何内容与使用 undefined.

解析相同

更新

pg-promise 不再支持生成器,因为较新的 NodeJS 使 async 语法标准,更适合任务回调。