给出一个类中的一个函数,该函数异步处理文本。我也希望我的班级有一个同步的同等学历。在以下示例中类似。请帮我实现它。
class Processor {
processAsync(text) {
return new Promise((resolve, reject) => {
anotherPromise(this.text).then(() => {
resolve(processedText);
}).catch((err) => {
reject(new Error(`PROMISES FAILED`));
});
});
}
// THIS IS THE FUNCTION I WANT TO WRITE WHICH RETURNS THE VALUE OF THE PROCESSED TEXT
processSync(text) {
return Promise.resolve(this.processAsync(text));
}
}
function anotherPromise(text) {
return new Promise((resolve, reject) => {
if (someConditionWithText) {
return resolve
}
return reject(someerror);
});
}
每当我打电话给processor.processSync('MyText')
时,它都会返回一个承诺值,而不是预期值。我必须做什么?我读到Promise.resolve()应该可以完成工作,但事实并非如此。
答案 0 :(得分:0)
您不能将原始的异步函数转换为同步函数,也不能使用原始的异步函数使其同步。一切都发生在异步函数中。因此,您必须复制异步函数并在内部进行修改。 processAsync返回承诺,因此在processSync中调用它时也会返回承诺。
class Processor {
processAsync(text) {
return new Promise((resolve, reject) => {
anotherPromise(this.text).then(() => {
// anotherPomise has logic for validating text
// and does something based on the text and resolve
let processedText = processText(process.env.SomeEnvironmentVariable, this.text);
resolve(processedText);
}).catch((err) => {
reject(new Error(`PROMISES FAILED`));
});
});
}
// THIS IS THE FUNCTION I WANT TO WRITE WHICH RETURNS THE VALUE OF THE PROCESSED TEXT
processSync(text) {
return processText(process.env.SomeEnvironmentVariable, this.text)
}
}