示例工程 07-async-promises
07-async-promises/01-three-styles/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
executorIsSynchronous,
loadAsync,
loadCallback,
loadPromise,
run,
thenFlattensPromises,
} from './main.js';
function callbackLoad(id) {
return new Promise((resolve) => loadCallback(id, (err, data) => resolve({ err, data })));
}
test('回调版:成功路径返回 { user, posts }', async () => {
const { err, data } = await callbackLoad(1);
assert.equal(err, null);
assert.deepEqual(data, {
user: { id: 1, name: 'user-1' },
posts: ['post-1-1', 'post-1-2'],
});
});
test('回调版:失败路径把错误交给第一个参数', async () => {
const { err, data } = await callbackLoad(0);
assert.match(err.message, /invalid id/);
assert.equal(data, undefined);
});
test('Promise 版与 async 版返回同一形状', async () => {
const a = await loadPromise(5);
const b = await loadAsync(5);
assert.deepEqual(a, b);
assert.equal(a.user.name, 'user-5');
});
test('new Promise 的执行器同步运行,then 回调异步运行', async () => {
assert.deepEqual(executorIsSynchronous(), ['before', 'executor', 'after']);
const order = [];
Promise.resolve().then(() => order.push('then'));
order.push('sync');
await Promise.resolve();
assert.deepEqual(order, ['sync', 'then']);
});
test('then 返回 Promise 会被展开,不是嵌套 Promise', async () => {
assert.equal(await thenFlattensPromises(), 20);
});
test('run 打印执行器顺序与说明', () => {
const out = [];
const lines = run((s) => out.push(s));
assert.equal(lines.length, 2);
assert.match(out[0], /before → executor → after/);
});