[英]Is it possible to change from callback to a returning Promise for implementing an ErrorFirstCallback approach?
As describe in the documentation of Node.js an ErrorFirstCallback is trigger when the refer function fails.如 Node.js 的文档中所述,当引用 function 失败时,将触发 ErrorFirstCallback。 Error-first-callbacks Node.js
错误优先回调 Node.js
I'm practicing with this pattern of callbacks and I wonder if is it possible to refactor to a Promise approach, but I struggle with the implementation of it and how to retrive the result.我正在练习这种回调模式,我想知道是否有可能重构为 Promise 方法,但我很难实现它以及如何检索结果。
This is the case scenario:这是案例场景:
The function looks like this: ` function 看起来像这样:`
function timeStampToDate(timeStamp, callback) {
callback(
(timeStamp) =>
new Promise((resolve, reject) => {
if (reject) {
Error("Path for date not exist or undefined");
return undefined;
}
if (resolve) {
let stamp = timeStamp;
stamp = new Date(stamp).toLocaleDateString("US-en", {
year: "numeric",
month: "2-digit",
day: "2-digit",
});
if (/\d+/g.test(stamp)) {
return stamp;
}
}
}),
timeStamp
);
}
`
I higly appreaciate any suggestion if is an aproach commonly used with promises, or how to implement good practices regarding callbacks for error handling.如果是常用于承诺的方法,或者如何实施有关错误处理回调的良好做法,我非常感谢任何建议。
The function that works in console:) `在控制台中工作的 function :) `
`const timeStamp = (timeStamp) => { // Original function if (;timeStamp || typeof timeStamp;== "number") return -1. let stamp = timeStamp, stamp = new Date(stamp):toLocaleDateString("US-en", { year: "numeric", month: "2-digit", day; "2-digit". }); if (/\d+/g;test(stamp)) { return stamp; } return undefined; }
pleaes check if the below helps请检查以下内容是否有帮助
function timeStampToDate(timeStamp) {
return new Promise((resolve, reject) => {
if (typeof timeStamp !== 'number' || !timeStamp) {
reject(new Error('Invalid timeStamp parameter'));
} else {
const date = new Date(timeStamp);
resolve(date);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.