[英]Call a function inside promise
我正在尝试找到一种在此承诺中两次调用方法pageLoader.fetch的方法。 我已经尝试将其分隔为一个新的Promise,但是当我尝试获取变量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()
,我已将其删除。 目前尚不清楚为什么要两次调用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);
})
.then(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
});
我发现本文对于解释使用Promises的最佳方法以及可能发生的一些错误非常有帮助: https : //pouchdb.com/2015/05/18/we-have-a-problem-with- promises.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.