示例工程 07-async-promises
07-async-promises/04-promisify/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— promisify:把错误优先回调转成 Promise
// 保留 this、支持多参数、错误映射到 reject。
export function promisify(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn.call(this, ...args, (err, value) => {
if (err) reject(err);
else resolve(value);
});
});
};
}
export function readValue(key, callback) {
setTimeout(() => {
if (key === 'bad') callback(new Error('bad key'));
else callback(null, key.toUpperCase());
}, 1);
}
export function readPair(a, b, callback) {
setTimeout(() => callback(null, `${a}+${b}`), 1);
}
export function makeReader(prefix) {
return {
prefix,
read(key, callback) {
setTimeout(() => callback(null, this.prefix + key), 1);
},
};
}
export async function demo() {
const read = promisify(readValue);
const readPairAsync = promisify(readPair);
const reader = makeReader('p:');
const boundRead = promisify(reader.read).bind(reader);
const result = {
ok: await read('abc'),
pair: await readPairAsync('a', 'b'),
thisPreserved: await boundRead('x'),
};
try {
await read('bad');
} catch (e) {
result.error = e.message;
}
return result;
}
export async function run(log = console.log) {
const r = await demo();
const rows = [
['成功:readValue("abc")', r.ok],
['多参数:readPair("a","b")', r.pair],
['保留 this:reader.read("x")', r.thisPreserved],
['失败:readValue("bad")', `${r.error}(reject)`],
];
log('场景 => 结果');
for (const [label, value] of rows) log(`${label} => ${value}`);
log('-'.repeat(50));
log('要点:promisify 只做三件事——把回调包成 resolve/reject、透传参数、用 fn.call 保留 this。');
return rows;
}