JavaScript承诺:使用非承诺对象链接承诺.为什么会这样?

Bru*_*res 3 javascript promise es6-promise

我正在学习JavaScript Fetch API,我对Promises有点困惑.

考虑这个在控制台中打印"ok"的虚拟示例:

fetch(".")
.then(function(response) { // first then() call
    return response;
}).then(function(response) { // second then() call
    console.log("ok");
});
Run Code Online (Sandbox Code Playgroud)

有关Fetch API 的响应对象的页面说:

fetch()调用返回一个promise,该promise使用与资源获取操作关联的Response对象解析.

好吧,既然fetch()返回一个Promise对象,我可以理解第一个then()调用工作正常,因为Promise对象有这个方法.但链接调用中返回的Response对象不是Promise对象.然而,then()方法的第二次调用工作!

改变虚拟示例打印undefined在第一个console.log():

fetch(".")
.then(function(response) { // first then() call
    console.log(response.then)
    return response;
}).then(function(response) { // second then() call
    console.log("ok");
});
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么这有效?then()自返回对象以来第二次调用如何工作没有这个方法?它是一种语法糖吗?

谢谢!

Ber*_*rgi 8

Response链接调用中返回的对象不是Promise对象.然而,then()方法的第二次调用工作!

是的,因为第二次.then()调用是第一次then调用的返回值,而不是响应.该承诺then方法总是会返回一个承诺 -这使得它可链接.它并没有返回异步回调的返回值-因为这将需要窥视到未来.

仔细看:

const promise1 = fetch(".");
const promise2 = promise1.then(function(response) { // first then() call
    return response;
});
const promise3 = promise2.then(function(response) { // second then() call
    console.log("ok");
});
Run Code Online (Sandbox Code Playgroud)

不是

fetch(".").then(function(response) { // outer then() call
    return response.then(function() { // inner then() call
        console.log("ok");
    });
});
Run Code Online (Sandbox Code Playgroud)

如果没有response承诺,这确实是行不通的.

  • 很棒的答案!谢谢!:) (2认同)