Answer the question
In order to leave comments, you need to log in
How are promises different from normal callbacks?
I posted this code here
function someAsyncFunction(num, callback) {
setTimeout( () => callback(num*2), 1500);
}
function promiseFunction(num) {
return new Promise((resolve, reject) => {
setInterval(() => resolve(num*2), 1500)
});
}
someAsyncFunction(10, res => console.log(res)); // Выведет 20 через 1,5 сек.
promiseFunction(10).then(res => console.log(res)); // Тот же результат
Answer the question
In order to leave comments, you need to log in
Not the same
function ajax() {
return fetch(target, fetchOptions)
.then((response) => {
if (!target) throw new Error('Invalid url');
if (response.ok) return response.json();
throw new Error(`${response.status} ${response.statusText}`);
})
.then((json) => {
if (json['statusOk']) return json;
throw new Error(json['message'] || 'Server response was not ok');
});
}
ajax(action, { body: formData })
.then((json) => {
console.log('RESPONSE', json);
})
.catch((error) => {
console.error(error);
});
function myFunc(cb){
var err = true;
// имитируем асинхронную операцию
setTimeout(function(){
cb(err);
}, 10);
}
try {
myFunc(function(err){
if (err) throw new Error('Oops');
});
alert('Всё как бы хорошо!');
} catch(e) {
alert(e.message);
}
function myFunc(){
let promise = new Promise((resolve, reject) => {
let err = true;
// имитируем асинхронную операцию
setTimeout(() => {
if (err) {
reject('Ooops!');
} else {
resolve(123);
}
}, 10);
});
return promise;
}
myFunc()
.then(data => {
alert('Всё точно хорошо!');
})
.catch(e => {
alert(e);
});
Two main differences:
There are no fundamental differences, both approaches are based on how the event loop works in JS and on the fact that the functions there are citizens of the first class. It's just more pleasant to work with promises.
A bunch of all kinds of methods bluebirdjs.com/docs/api-reference.html
And the need to pass errors as the first argument
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question