I tried testing the example given in MDN in one of the promise implementation. Its giving me the error as below.
Error
Uncaught TypeError: doSomething(...).then is not a function
at promise.js:16
JS file
function successCallback(result) {
console.log("Success" + result);
}
function failCallback(fail) {
console.log('fail' + fail);
}
function doSomething(successCallback, failCallback) {
return "Yello";
};
doSomething(successCallback, failCallback);
doSomething().then(successCallback,failCallback);
Even easier with async :
async function doSomething() {
return "Yello";
};
doSomething().then(console.log);//Yello
To enable error handling, simply throw an error:
async function isMultiple(a,b) {
if(a%b===0){
return true;//success
}
throw "not a multiple";
};
isMultiple(5,2).then(console.log).catch(console.log);//not a multiple in catch
Note that async functions are part of ES7 ( very very new )...
babeled code
You'll have to return a Promise which resolves
in the case of success or rejects
in case of error to the then
.
function successCallback(result) {
console.log("Success" + result);
}
function failCallback(fail) {
console.log('fail' + fail);
}
function doSomething(successCallback, failCallback) {
return new Promise( (resolve, reject) => {
resolve('Yello!');
// or
// reject ("Error!");
});
}
doSomething().then(successCallback, failCallback);
In your example, you are not using a Promise
. To use one, you must do :
function successCallback(result) {
console.log("Success" + result);
}
function failCallback(fail) {
console.log('fail' + fail);
}
function doSomething() {
return new Promise(function(resolve,reject) {
console.log("Yello");
resolve();
});
}
doSomething().then(successCallback,failCallback);
Here, the failCallback
will never be executed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With