1 回答
TA贡献2041条经验 获得超4个赞
如果返回 promise,则可以编写如下相同的代码:client.exists
empId: async (obj, params, ctx, resolverInfo) => {
const exists = await client.exists(obj.empId);
if (exists === 1) {
return getAsync(obj.empId);
}
return await db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
.then(iuidtest => {
return iuidtest.empid;
});
}
如果只接受回调,则代码可以写成:client.exists
empId: async (obj, params, ctx, resolverInfo) => {
async function empIdExists(empId) {
return new Promise(function resolver(resolve, reject) {
client.exists(obj.empId, function(err, reply) {
if (err) {
reject(err);
return;
}
if (reply == 1) {
resolve(1);
return;
} else {
resolve(0);
return;
}
})
});
}
const exists = await empIdExists(obj.empId);
if (exists === 1) {
return getAsync(obj.empId);
}
return await db.one('SELECT * FROM iuidtest WHERE empid = $1', [obj.empId])
.then(iuidtest => {
return iuidtest.empid;
});
}
在第二个版本中,请注意,我已将调用包装到异步函数中,并使用关键字调用。client.existsawait
添加回答
举报