Why does a Promise return an object Promise, even if I put `return` explicitly? [duplicate]

允我心安 提交于 2021-02-10 12:20:07

问题


I expected a Promise will return a value that I put. But It doesn't return a value but returns Promise { pending }

var c = new Promise((resolve, reject)=>{
    console.log('here');
    return 'return here';
    // resolve('resolve here')
});

console.log(c);

I expected there will be return here instead of Promise { pending }


回答1:


Why does a Promise return an object Promise, even if I put return explicitly?

Well, because that's not how promises are designed. The return value from the promise executor callback function is not used at all.

If you want to know why it wasn't designed the way you want it to be designed, you'd have to go find the actual engineers who were involved in the early design of the Promise constructor and its executor function.

Relevant to us is "how it works", not really why one design path was selected vs another. var c = new Promise(...) always returns a newly created promise just like most would expect it to.

And, the promise executor function is used to allow you to start your asynchronous operation and then eventually track its completion or error with resolve() or reject(). There are no code paths where you instead decided you're going to return a value so that new Promise() should just return that value instead of returning a new promise. So, as most would expect new Promise() always returns a promise, regardless of what you do in the promise executor callback function.

As you appear to already know, if you want to immediately set the resolved value of the promise, then you call resolve(someValue) and that sets the resolved value of the promise.

You get values out of a promise with .then() or with await. Those are the only two ways.

I expected there will be return here instead of Promise { pending }

First off, you have to realize that the promise executor callback function is a function you provided the new Promise() constructor. That constructor creates a new promise object, creates unique resolve and reject functions and passes them as arguments to that callback function you provided and it calls that function. It doesn't pay any attention to the return value from that function. The designers of this executor function and the whole promise initialization process decided that the return value of that function was irrelevant. There are two ways to change the state of the new promise, by calling resolve(someValue) or reject(someReason). Only those two ways.

Second off, understand that the return in that function is just returning back from the callback function you provided and the flow of execution finishes up in the Promise constructor and then it returns from the new Promise() constructor and assigns that new promise to your variable c. A new Promise has been created at that point. If the promise executor did not call resolve() or reject() yet that new promise will be in the pending state. If resolve() or reject() was called immediately, then the promise may be fulfilled or rejected (the other two states it can be in).

There is no scenario where new Promise() returns your value.

In your specific code (with the call to resolve() put back in), you can get the value from the promise either like this with.then()`:

let c = new Promise((resolve, reject)=>{
    console.log('here');
    resolve('resolve here');
}).then(val => {
    console.log(val);
});

Or using await (inside an async function):

async function someFunction() {
    let c = new Promise((resolve, reject)=>{
        console.log('here');
        resolve('resolve here');
    });
    let val = await c;
    console.log(val);
}



回答2:


cause its not resolved yet, resolve or reject is the end value https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise




回答3:


This is not how promises work. The point of the promise is to control the execution flow. You will not get a value until the promise is resolved:

var c = new Promise((resolve, reject)=>{
    console.log('here');
    // return 'return here';
    resolve('resolve here')
});

c.then(result => {
   console.log(result)
})



回答4:


A promise represents an asynchronous computation, so you can't access its result synchronously, you need to chain a callback with .then(), see the doc here.

Here is a working example:

const c = new Promise((resolve, reject)=>{
    resolve('resolve here')
});

c.then(value => console.log(value));



回答5:


That's not the correct way of using Promises. You will have to resolve promise and use then method to see resolved promise.

You will have to do as:

var c = new Promise((resolve, reject)=>{
    console.log('here');
    //return 'return here';
    resolve('resolve here')
});

c.then(function(value) {
  console.log(value);
});



回答6:


You should use resolve instead of return. Above has answered your questions perfectly.

const c = new Promise((resolve, reject)=>{
  console.log('here');
  resolve('resolve here')
});
c().then((answer) => console.log(answer))


来源:https://stackoverflow.com/questions/57504663/why-does-a-promise-return-an-object-promise-even-if-i-put-return-explicitly

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