Вы можете использовать синтаксис ES7 async/await
с обещанием .В вашем методе hello1()
вы можете вернуть обещание, которое будет alert()
, а затем resolve
, чтобы указать, что ваш метод hello1
завершен.Затем saythehellos()
будет ждать от hello1()
до resolve
(поскольку мы используем ключевое слово await
), а затем он продолжит выполнение hello2()
:
function hello1() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
alert("hello1");
resolve();
}, 500);
});
}
function hello2() {
alert("hello2");
}
async function saythehellos() { // make async as we want to use await within this method
await hello1();
hello2();
}
saythehellos();
В качестве альтернативы, если вы ищете что-то более совместимое с браузером, вы можете использовать обратный вызов .then
для возвращенного обещания от hello1()
(что по сутичто async/await
делает под капотом).Обратный вызов .then
будет запущен, когда возвращенный promise
разрешится:
function hello1() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
alert("hello1");
resolve();
}, 500);
});
}
function hello2() {
alert("hello2");
}
function saythehellos() {
hello1().then(function(result) {
hello2();
});
}
saythehellos();