[英]Promisify a curried (higher order function) callback
我正在嘗試承諾(或利用異步等待功能)function getId 中的回調,使用 new Promise(resolve =>...,但由於使用了更高階的 function getAddresses,我有點難過。我不擅長函數式編程。關於我如何承諾這個有什么建議嗎?
const {queryRecord, getData} = require(“@xyzLib”);
const getId = (callback) => {
getData(“attr1”,”attr2”,getAddresses(callback));
}
const getAddresses = (callback) => (result) => {
if (!result.success) {
callback(new Error(‘Exception details’))
} else {
queryRecord(objectName, (result) => {
callback(null, result.name);
});
}
}
// invoking call
getId(async (error, zip, state) => {
if (error) {
console.log(error.message)
} else {
await fetch(encodeURI(settingsUrl), {
method: 'GET',
});
....
由於getId()
接受回調作為最后一個參數,並且該回調使用 nodejs 調用約定,因此您可以直接在getId
上使用util.promisify()
,如下所示:
const { promisify } = require('util');
const getIdPromise = promisify(getId);
getIdPromise().then(result => {
console.log(result);
let fetchResult = await fetch(...);
...
}).catch(err => {
console.log(err);
});
或者,如果您已經在async
function 正文中:
try {
const result = await getIdPromise();
console.log(result);
const fetchResult = await fetch(...);
...
} catch (err) {
console.log(err);
}
您應該在可用的最低級別上進行承諾,即從庫中導入的函數。 那么你甚至不需要柯里化。 和
const { promisify } = require('util');
const xyz = require(“@xyzLib”);
const queryRecord = promisify(xyz.queryRecord);
const getData = promisify(xyz.getData);
你可以簡單地寫
async function getId() {
return getAddresses(await getData("attr1", "attr2"));
}
async function getAddresses(data) {
if (!data.success) throw new Error("Exception details");
const result = await queryRecord(objectName);
return result.name;
}
// invoking call
try {
const zip = getId();
await fetch(encodeURI(settingsUrl), {
method: 'GET',
});
} catch(error) {
console.log(error.message);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.