我正在研究Electron in Action。我正在移动中学习JavaScript,但这并没有出现在谷歌中,所以我想我会在这里问它。想象一下,我们有这个代码:
newLinkForm.addEventListener('submit', (event) => {
event.preventDefault();
const url = newLinkUrl.value;
fetch(url)
.then(response => response.text())
.then(parseResponse)
.then(findTitle)
.then(title => storeLink(title, url))
.then(clearForm);
});
在链的第一个和第四个环中,我们为第0个和第三个函数的返回值命名。但是如果有多个返回值呢?我们创建一个列表吗?我们可以在promise链中调用两个函数,如:
then(returnvalue1=>funct1, returnvalue2=>funct2)
我们可以这样做吗?谢谢你的回复。
第二个then
参数是为错误处理程序保留的,then(returnvalue1=>funct1, returnvalue2=>funct2)
不是一个正确的方法来处理返回值。
then
回调只接收一个返回值作为参数,这是前一个then
回调返回的值。
如果需要同时使用来自不同then
的值,它们应该作为数组或对象值传递到整个promise链并进行解构:
promise
.then(foo => {
const bar = 'bar';
return [foo, bar];
})
.then(([foo, bar]) => {
// can access both foo and bar
})
或者then
应该嵌套以访问可用必要值的范围:
promise
.then(foo => {
const bar = 'bar';
return Promise.resolve(bar);
.then(bar => {
// can access both foo and bar
})
})
这是async..await
解决的问题之一。
承诺只有一个已解析的值,因此.then()
处理程序只传递一个参数。
如果要使用多个值来解析promise,那么通常将它们包装在数组或对象中,单个已解析的值将是数组或对象。
您可以使用解构来轻松引用包含在对象或数组中的多个值。
例:
Promise.resolve([1,2]).then(result => {
console.log(result); // logs [1,2]
return result; // pass the array on to the next step
}).then(([a, b]) => { // use destructuring to get the two items out of the array
console.log(a);
console.log(b);
});
你提出这样的建议:
.then(returnvalue1=>funct1, returnvalue2=>funct2)
是完全不同的东西。在这里你将两个函数传递给.then()
,就像在.then(f1, f2)
中一样(或者看起来就像你想要做的那样)。当你将第二个函数传递给.then()
时,第二个函数是拒绝处理程序(如.catch()
处理程序),只有当promise拒绝并且参数将是拒绝原因时才会调用它。