Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is then not working on this function

Tags:

javascript

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);
like image 374
user3310115 Avatar asked Jun 24 '17 09:06

user3310115


3 Answers

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

like image 124
Jonas Wilms Avatar answered Oct 12 '22 09:10

Jonas Wilms


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);
like image 40
Dan Philip Avatar answered Oct 12 '22 10:10

Dan Philip


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

like image 33
Xatyrian Avatar answered Oct 12 '22 09:10

Xatyrian