Om client.exists
returnerar löfte, samma kod kan skrivas som nedan:
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;
});
}
Om client.exists
accepterar endast återuppringning, då kan koden skrivas som:
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;
});
}
I den andra versionen, lägg märke till att jag har packat in client.exists
anropa en asynkronfunktion &anropa med await
nyckelord.