从 Promise 构造函数返回值 [英] Return value from a Promise constructor

查看:29
本文介绍了从 Promise 构造函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的两个例子......

Consider two examples below...

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

它什么都不输出.

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

它输出:

DATA: 123
VALUE: 456

promise 构造函数不简单地解析 TEST 1 中的返回值有哪些缺点或规范矛盾?

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

为什么它必须与测试 2 中的结果不同?

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

我试图根据 promise 规范.

推荐答案

传递给 Promise 的函数不是 onFulfilledonRejected.MDN 称它为 executor.将其视为 Promise 试图捕获的异步上下文.从异步方法返回不起作用(或没有意义),因此您必须调用 resolvereject.例如

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

... 无法按预期工作.如果您要在异步调用完成之前从 executor 返回一个值,则无法重新解析承诺.

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

此外,函数末尾的隐式 return undefined; 可能会产生歧义.考虑这些以相同方式运行的执行器.

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() { }

什么会告诉 Promise 构造函数你真的想用 undefined 解析?

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

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

这篇关于从 Promise 构造函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆