Javascript 在promise中调用函数
我正在试图找到一种方法,在这个承诺中调用pageLoader.fetch方法两次。我已经尝试在一个新的promise中分离它,但是当我尝试获取变量链接[0]时,我没有定义它。如何做到这一点Javascript 在promise中调用函数,javascript,promise,Javascript,Promise,我正在试图找到一种方法,在这个承诺中调用pageLoader.fetch方法两次。我已经尝试在一个新的promise中分离它,但是当我尝试获取变量链接[0]时,我没有定义它。如何做到这一点 pageLoader .fetch(url) .then(function(data) { links = html.orderdList(data); }) .then(function() { return pageLoader.fetch(links[0]); /
pageLoader
.fetch(url)
.then(function(data) {
links = html.orderdList(data);
})
.then(function() {
return pageLoader.fetch(links[0]);
//links[0] is undefined in the next line!?
})
.then(
pageLoader
.fetch(links[0])
.then(function(innerLinks) {
calLinks = html.unorderList(innerLinks);
})
.then(function() {
return pageLoader.fetch("http:///example.com");
})
.catch(function(error) {
console.log(error);
})
);
你快到了。你有一些多余的,
then()
s,我已经删除了。不清楚为什么要调用pageLoader.fetch(links[0])
两次。它会返回不同的结果吗
您看起来还设置了一些全局变量(links
&calLinks
),但不清楚如何异步访问它们
这应该会更好一些,但鉴于上述情况,它可能仍然存在问题:
pageLoader.fetch(url)
.then(function(data) {
links = html.orderdList(data); // <-- are these global or should you have a var?;
return pageLoader.fetch(links[0]);
})
.then(function(link) { // <-- did you want to do something with the return from above?
return pageLoader.fetch(links[0])
})
.then(function(innerLinks) {
calLinks = html.unorderList(innerLinks); // <-- are these global?;
return pageLoader.fetch("http:///example.com");
})
.catch(function(error) {
console.log(error);
})
pageLoader.fetch(url)
.then(功能(数据){
links=html.orderdList(data);//行。然后(pageLoader.fetch(links[0])…
没有执行您可能希望它执行的操作。这样调用它相当于执行以下操作:
var myCallback = pageLoader.fetch(links[0]).then().then().catch();
pageLoader
.fetch(url)
.then(function(data) {
links = html.orderdList(data);
})
.then(function() {
return pageLoader.fetch(links[0]);
})
.then(myCallback)
您的第二次提取实际上是在执行其他操作之前立即执行的,其结果作为回调传递。您可能希望在第一次fetch
执行之前不调用该代码,因此您希望将其包装在函数中(与其他.then()
语句类似)
我还建议您可以大大简化代码:
pageLoader
.fetch(url)
.then(function(data) {
// this is called when the first fetch() returns
links = html.orderdList(data);
return pageLoader.fetch(links[0]);
// returning a promise means that following .then()
// statements will act on the returned promise rather than the original
})
.then(function(innerLinks) {
// this is called when the second fetch() returns
calLinks = html.unorderList(innerLinks);
return pageLoader.fetch("http:///example.com");
})
.catch(function() {
// this is called if the original promise or any of
// the promises returned in the .then() callbacks throw errors
});
我发现本文非常有助于解释使用承诺的最佳方式,以及可能发生的一些错误:return
语句停止当前函数的执行。注意:(pageLoader.fetch…
-错误…。那么
仅在作为argumentpageLoader提供函数时有效。fetch(链接[0])返回从pageLoader.fetch(url)获取的新urlpage@Jason-我明白了,您使用相同的索引pageLoader.fetch(链接[0])调用了它两次
这就是我感到困惑的原因。link和calLinks是全球性的