Перейти к основному содержимому
  • Урок 12 из 14

Промисы и async/await

После урока вы сможете

  • Создавать и цепочить Promise через then/catch/finally
  • Писать async-функции и await без распространённых ловушек
  • Выбирать Promise.all, race, allSettled под задачу

Асинхронность в JS строится на колбэках, затем на , затем на синтаксисе async/await.

Зачем не только колбэки​

function loadLegacy(cb) {
setTimeout(() => cb(null, { ok: true }), 50);
}

loadLegacy((err, data) => {
if (err) console.error(err);
else console.log(data);
});

Вложенность растёт при последовательных шагах. Промисы выравнивают цепочку.

Создание Promise​

const p = new Promise((resolve, reject) => {
const ok = true;
if (ok) resolve(42);
else reject(new Error("fail"));
});

p.then((value) => console.log("ok", value)).catch((err) =>
console.error("err", err),
);

Состояния: pending, fulfilled, rejected. Переход одноразовый.

Обёртка таймера:

function delay(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}

delay(100, "done").then(console.log);

Promise.resolve / Promise.reject:

Promise.resolve(1).then(console.log);
Promise.reject(new Error("x")).catch((e) => console.log(e.message));

then / catch / finally​

Promise.resolve(2)
.then((n) => n * 3)
.then((n) => {
console.log(n); // 6
return n;
})
.catch((err) => {
console.error(err);
return 0;
})
.finally(() => {
console.log("cleanup");
});

then возвращает новый промис. Если колбэк вернул значение — оно станет fulfillment; если бросил/вернул rejected — пойдёт в catch.

Promise.resolve(1)
.then(() => {
throw new Error("boom");
})
.catch((e) => {
console.log("caught", e.message);
return 10;
})
.then((v) => console.log("next", v));

Микротаски​

console.log("A");
Promise.resolve().then(() => console.log("B"));
console.log("C");
// A C B

Колбэки промисов — микротаски; setTimeout — макротаски. Порядок важен в тонкой отладке.

async / await​

async функция всегда возвращает Promise:

async function answer() {
return 42;
}

answer().then(console.log);

await ждёт промис внутри async:

async function run() {
const value = await delay(50, "hi");
console.log(value);
return value;
}

run();

Обработка ошибок — try/catch:

async function load() {
try {
const data = await Promise.reject(new Error("network"));
return data;
} catch (err) {
console.error(err.message);
return null;
} finally {
console.log("done");
}
}

load();

Последовательность vs параллель​

Последовательно:

async function seq() {
const a = await delay(50, 1);
const b = await delay(50, 2);
return a + b;
}

Параллельно:

async function par() {
const [a, b] = await Promise.all([delay(50, 1), delay(50, 2)]);
return a + b;
}

Нечаянная последовательность в цикле:

async function slowMap(xs) {
const out = [];
for (const x of xs) {
out.push(await delay(10, x * 2)); // ждет по одному
}
return out;
}

async function fastMap(xs) {
return Promise.all(xs.map((x) => delay(10, x * 2)));
}

Promise.all​

Все успешны → массив результатов. Любой reject → весь промис reject (остальные не отменяются сами по себе).

Promise.all([Promise.resolve(1), Promise.resolve(2)]).then(console.log);

Promise.all([Promise.resolve(1), Promise.reject(new Error("x"))]).catch((e) =>
console.log(e.message),
);

Promise.allSettled​

Ждёт все; результат — статусы:

Promise.allSettled([
Promise.resolve(1),
Promise.reject(new Error("x")),
]).then(console.log);
// [{status:"fulfilled", value:1}, {status:"rejected", reason: Error}]

Удобно, когда частичный успех допустим.

Promise.race​

Первый settled побеждает:

function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error("timeout")), ms);
});
return Promise.race([promise, timeout]);
}

withTimeout(delay(200, "ok"), 50).catch((e) => console.log(e.message));

Promise.any (кратко)​

Первый fulfillment; если все rejected — AggregateError. Полезно для «первый успешный источник».

Promise.any([
Promise.reject(new Error("a")),
Promise.resolve("b"),
]).then(console.log); // b

Преобразование колбэков​

function readFake(path) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!path) reject(new Error("path"));
else resolve("contents of " + path);
}, 20);
});
}

async function main() {
const text = await readFake("a.txt");
console.log(text);
}

main();

В Node часто есть fs.promises / util.promisify.

Ошибки: забытый await / catch​

async function oops() {
Promise.reject(new Error("lost")); // не await и нет catch — unhandled rejection
}

async function better() {
await Promise.reject(new Error("caught later"));
}

better().catch((e) => console.log(e.message));

Всегда либо await в try/catch, либо .catch на промисе.

Практика: retry​

async function retry(fn, times = 3) {
let last;
for (let i = 0; i < times; i += 1) {
try {
return await fn(i);
} catch (err) {
last = err;
await delay(20 * (i + 1));
}
}
throw last;
}

retry(async (i) => {
if (i < 2) throw new Error("try " + i);
return "ok";
}).then(console.log);

Практика: очередь ограниченных задач​

async function mapPool(items, limit, worker) {
const results = new Array(items.length);
let next = 0;

async function run() {
while (next < items.length) {
const i = next;
next += 1;
results[i] = await worker(items[i], i);
}
}

const runners = Array.from({ length: Math.min(limit, items.length) }, () =>
run(),
);
await Promise.all(runners);
return results;
}

mapPool([1, 2, 3, 4], 2, async (n) => {
await delay(30);
return n * 2;
}).then(console.log);

Практика: fetch-стиль (идея)​

async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}

// getJson("https://example.com").then(...).catch(...)

В Node 18+ fetch есть глобально; в браузере — давно.

Частые ошибки​

  1. await в обычной (не async) функции — SyntaxError.
  2. Цепочка без return внутри then — потеряли следующий шаг.
  3. Promise.all там, где нужен частичный успех — берите allSettled.
  4. Последовательные await в цикле без нужды.
  5. Проглатывание ошибок пустым catch.
async function demo() {
const p = delay(10, 1);
return p; // ок — вернётся промис
}

top-level await (намёк)​

В ES-модулях современных сред допускается await на верхнем уровне файла:

// только в ESM-модуле поддерживающей среды
const data = await Promise.resolve({ ok: true });
console.log(data);

В Ordinary script / старом CJS — нет. Для утилит CLI в Node ESM это удобно; в библиотеках осторожнее — модуль станет асинхронно вычисляемым.

Итог​

Промис моделирует будущий результат; async/await делает последовательный асинхронный код читаемым. Комбинаторы управляют параллелизмом. Дальше — ошибки и отладка.

Что вернёт async-функция, если внутри return 1?

const thenable = {
then(resolve) {
resolve(99);
},
};

Promise.resolve(thenable).then(console.log); // 99

Объект с методом then может вести себя как промис (thenable). await тоже это учитывает.

Чеклист готовности​

Я уверенно умею

0 / 4 выполнено

Дочитали до конца?

Отметьте урок пройденным — так проще вернуться туда, где остановились.

Основы языка: 0 из 14