Return value from a Promise constructor

眉间皱痕 提交于 2021-02-01 18:08:17

问题


Consider two examples below...

TEST 1

function test1() {
    return new Promise(function () {
        return 123;
    });
}

test1()
    .then(function (data) {
        console.log("DATA:", data);
        return 456;
    })
    .then(function (value) {
        console.log("VALUE:", value);
    });

It outputs nothing.

TEST 2

function test2() {
    return new Promise(function (resolve, reject) {
        resolve(123);
    });
}

test2()
    .then(function (data) {
        console.log("DATA:", data);
        return 456;
    })
    .then(function (value) {
        console.log("VALUE:", value);
    });

It outputs:

DATA: 123
VALUE: 456

What are the drawbacks or spec contradictions for a promise constructor not to simply resolve a returned value in TEST 1?

Why does it have to be a different result than in TEST 2?

I'm trying to understand how a constructed promise object is different from a then-able object as per the promise spec.


回答1:


The function passed to Promise isn't a callback for onFulfilled or onRejected. MDN calls it the executor. Think of it as the async context that the promise is attempting to capture. Returning from an async method doesn't work (or make sense), hence you have to call resolve or reject. For example

var returnVal = new Promise(function() {
     return setTimeout(function() {
         return 27;
     });
});

... does not work as intended. If you were to return a value from the executor before your async calls finished, the promise couldn't be re-resolved.

Also, it could be ambigous with the implicit return undefined; at the end of the function. Consider these executors that function the same way.

// A
function a() { return undefined; }

// B
function b() { }

What would tell the Promise constructor that you really wanted to resolve with undefined?

a() === b(); // true



回答2:


It's worth mentioning that there is a shorthand for returning a resolved promise, Promise.resolve.

return new Promise(function (resolve, reject) {
    resolve(123);
});

simply becomes

return Promise.resolve(123);


来源:https://stackoverflow.com/questions/32780377/return-value-from-a-promise-constructor

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