Why does this simple JS promise return a promise? [duplicate]

删除回忆录丶 提交于 2021-01-28 09:54:34

问题


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");
  });
}

回答1:


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");
      });
    }



回答2:


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))



来源:https://stackoverflow.com/questions/56134951/why-does-this-simple-js-promise-return-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!