Сергей Жигалов
В любой момент времени, любой участок кода исполняется в единственном потоке.
let counter = 0;
counter++;
console.log(counter); // 1
console.log('Я выполняюсь сейчас');
setTimeout(() => {
console.log('Я выполнюсь позже');
}, 5000);
console.log('Я тоже выполняюсь сейчас');
console.log('Я выполняюсь сейчас');
setTimeout(() => {
console.log('Я выполнюсь позже');
}, 5000);
console.log('Я тоже выполняюсь сейчас');
console.log('Я выполняюсь сейчас');
setTimeout(() => {
console.log('Я выполнюсь позже');
}, 5000);
console.log('Я тоже выполняюсь сейчас');
const eventLoop = [];
while (true) {
if (eventLoop.length > 0) {
const event = eventLoop.shift();
event();
}
}
Hey, I'm going to suspend execution for now, but whenever you finish with that network request, and you have some data, please call this function back."
setTimeout(() => {
console.log('Я выполнюсь через 5 секунд');
}, 5000);
const cb = (error, data) => {
if(error) {
console.error(error);
} else {
console.log(data);
}
}
console.log('A');
setTimeout(() => {
console.log('B');
setTimeout(() => console.log('C'));
console.log('D');
});
console.log('E');
setTimeout(() => {
fs.readFile('./path.json', (err, data) => {
request(data.url, (err, res, body) => {
setTimeout(() => {
const data = JSON.parse(body);
console.log(data.fact);
}, 1000);
});
});
}, 5000);
Получить текущую температуру воздуха при помощи API погоды
const getWeather = require('./getWeather');
getWeather(54, (error, temp) => {
if (error) {
console.error(error);
} else {
console.log(temp); // -3
}
});
const request = require('request');
const getWeather = (geoid, cb) => {
const url = `https://.../?geoid=${geoid}`;
request(url, (err, res, body) => {
if (err) {
cb(err);
} else {
const data = JSON.parse(body);
cb(null, data.fact.temp);
}
});
}
module.exports = getWeather;
const request = require('request');
const getWeather = (geoid, cb) => {
const url = `https://.../?geoid=${geoid}`;
request(url, (err, res, body) => {
if (err) {
cb(err);
} else {
const data = JSON.parse(body);
cb(null, data.fact.temp);
}
});
}
module.exports = getWeather;
Error 404: Not found :-(
Вычислить среднюю температуру воздуха по области используя API погоды
const getWeather = require('./getWeather');
getWeather(54, (err, t1) => {
getWeather(2, (err, t2) => {
getWeather(5, (err, t3) => {
console.log((t1 + t2 + t3) / 3);
});
});
});
const getWeather = require('./getWeather');
console.time('time');
getWeather(54, (err, t1) => {
getWeather(2, (err, t2) => {
getWeather(5, (err, t3) => {
console.log((t1 + t2 + t3) / 3);
console.timeEnd('time'); // 691ms
});
});
});
const t = [];
const cb = (err, temp) => {
t.push(temp);
if(t.length === 3) {
console.log((t[0] + t[1] + t[2]) / 3);
}
}
getWeather(54, cb);
getWeather(2, cb);
getWeather(5, cb);
const getWeather = require('./getWeather');
const async = require('async');
async.parallel([
cb => getWeather(54, cb),
cb => getWeather(2, cb),
cb => getWeather(5, cb)
], (err, t) => {
console.log((t[0] + t[1] + t[2]) / 3);
});
const getWeather = require('./getWeather');
getWeather(54, (error, temp) => {
if (error) {
console.error(error);
} else {
console.log(temp);
}
});
const getWeather = require('./getWeather');
getWeather(54)
.then(temp => console.log(temp))
.catch(error => console.error(error));
const getWeather = require('./getWeather');
getWeather(54)
.then(console.log)
.catch(console.error);
waitAllAsync([
getWeather(54),
getWeather(2),
getWeather(5)
])
.then(t => console.log((t[0] + t[1] + t[2]) / 3))
.catch(console.error)
const request = require('request');
const getWeather =
geoid => new Promise((resolve, reject) => {
const url = `https://.../?geoid=${geoid}`;
request(url, (err, res, body) => {
if (err) {
reject(err);
} else {
const data = JSON.parse(body);
resolve(data.fact.temp);
}
});
});
module.exports = getWeather;
const getWeather = require('./getWeather');
getWeather(54)
.then(console.log, console.error);
resolve
reject
Вызов метода .then
возвращает новый промис
const identity = data => data;
const thrower = error => { throw error; };
const getWeather = require('./getWeather');
getWeather(54)
.then(console.log, console.error);
const getWeather = require('./getWeather');
getWeather(54)
.then(console.log, thrower)
.then(identity, console.error);
Получить температуру воздуха при помощи API погоды и записать результат в файл.
const request = require('request');
const getWeather =
geoid => new Promise((resolve, reject) => {
const url = `https://.../?geoid=${geoid}`;
request(url, (err, res, body) => err ?
reject(err) :
resolve(body));
});
getWeather(54)
.then(JSON.parse, thrower)
.then(identity, () => ({ fact: { temp: 0 } }))
.then(
data => console.log(data.fact.temp),
thrower
);
const fs = require('fs');
const saveToFile =
data => new Promise((resolve, reject) => {
fs.writeFile('./result.json', data, err => err ?
reject(err) :
resolve('success'));
});
getWeather(54)
.then(JSON.parse, thrower)
.then(identity, () => ({ fact: { temp: 0 } }))
.then(
data => saveToFile(data.fact.temp)
.then(console.log, thrower)
.then(identity, console.error),
thrower
);
В .then
можно передать функцию, которая вернет промис.
Выполнение цепочки продолжится когда промис выполнится.
getWeather(54)
.then(JSON.parse, thrower)
.then(identity, () => ({ fact: { temp: 0 } }))
.then(
data => saveToFile(data.fact.temp),
thrower
)
.then(console.log, thrower)
.then(identity, console.error);
getWeather(54)
.then(JSON.parse, thrower)
.then(identity, () => ({ fact: { temp: 0 } }))
.then(
data => saveToFile(data.fact.temp),
thrower
)
.then(console.log, thrower)
.then(identity, console.error);
getWeather(54)
.then(JSON.parse)
.catch(() => ({ fact: { temp: 0 } }))
.then(data => saveToFile(data.fact.temp))
.then(console.log)
.catch(console.error);
Promise.all([
getWeather(54),
getWeather(2),
getWeather(5)
])
.then(t => console.log((t[0] + t[1] + t[2]) / 3))
.catch(console.error)
Promise
.resolve(' УДАЛЯЕМ Лишние пробелы ')
.then(data => data.trim())
.then(data => data.replace(/\s+/g, ' '))
.then(data => data.toLowerCase())
.then(console.log);
// удаляем лишние пробелы
Promise
.reject('error')
.then(identity, console.error); // "error"
const Promise = require('bluebird');
Promise
.props({
ekb: getWeather(54),
spb: getWeather(2),
msk: getWeather(5)
})
.then(({ ekb, spb, msk }) => {
console.log((ekb + spb + msk) / 3);
});
getWeather(54)
.then(JSON.parse)
.catch(() => ({ fact: { temp: 0 } }))
.then(console.log)
.catch(console.error);
try {
const body = await getWeather(geoid);
return JSON.parse(body);
} catch (error) {
return { fact: { temp: 0 } };
}
await
указывает на то,
что нужно дождаться выполнение промиса.
Если промис зарезолвился - вернется результат,
иначе возникнет исключение.
const getTempData = async geoid => {
try {
const body = await getWeather(geoid);
return JSON.parse(body);
} catch (error) {
return { fact: { temp: 0 } };
}
}
При вызове асинхронной функции получаем promise
const run = async () => {
const data = await getTempData(54);
return await saveToFile(data.fact.temp);
}
run()
.then(console.log)
.catch(console.error);