1

A really simply question. I've boiled it down to the simplest version that illustrates my problem.

Why does this vanilla JS return a promise, and how can I get it to return "Hello"?

    
let result = test()
  .then(function(result) {
     return result;
  });

alert(result);
    
function test(serialized) {
  return new Promise(function(resolve, reject) {
    resolve("Hello");
  });
}

2
  • What do you mean by "returns a promise"? What behavior do you want to achieve?
    – yeputons
    Commented May 14, 2019 at 16:40
  • Just use:- (async () => { alert(await test()) })(); to get the result from test..! Commented May 14, 2019 at 16:47

2 Answers 2

2

What's happening is that you are "alerting" the value returned by the then method.

The then method will always return a promise, even if you are returning a value, it's wrapped in a resolved promise (e.g. Promise.resolve('Hello')), this allows you to achieve chainability, for instance you can call and return other promises in the then callback, and they will wait the resolution to continue and resolve.

  test()
      .then(function(result) {
        console.log(result);
        return result + ' world!';
      }).then(function(result2) {
        console.log(result2); // Hello world!
        return new Promise(function (resolve) { resolve('End') });
      }).then(function (result) {
         console.log(result);
      })
    
    
    function test(serialized) {
      return new Promise(function(resolve, reject) {
        resolve("Hello");
      });
    }

0

promise.then((result) => {}) always return another promise, so that we can chain multiple .then() calls.

how can I get it to return "Hello"? : For this you must await a promise.

for eg: alert(await test()) problem is that you can use await only within an async function.

Another option is to alert within then. test().then((result) => alert(result))

Not the answer you're looking for? Browse other questions tagged or ask your own question.