5

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);
user3310115
  • 1,372
  • 2
  • 18
  • 48
  • There's not promise to be seen in your code. – robertklep Jun 24 '17 at 10:01
  • You defined a function called doSomething, not a promise – Omri Luzon Jun 24 '17 at 10:01
  • then what is given in this url? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises – user3310115 Jun 24 '17 at 10:03
  • 2
    The example they show assumes a function that returns a promise, and they contrast it with a function that accepts callbacks. There's nothing magic about promises or functions that return them-it's normal JavaScript, and you still need an object to call "then" on. – Dave Newton Jun 24 '17 at 10:34

5 Answers5

6

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

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
3

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);
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33
2

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

Xatyrian
  • 1,364
  • 8
  • 26
1

Your doSomething function has to return a Promise. For Example:

return Promise.resolve('Hello');

MadClown
  • 124
  • 7
0

doSomething Object does not have then function , doSomething is just a function

Srinivas ML
  • 732
  • 3
  • 12