我正在学习如何使用 Promises。我有以下函数返回第“i”个 xkcd 漫画标题作为 promise :
var xkcd = function(i) {
return new Promise(
function(resolve, reject) {
var tempurl = 'https://www.xkcd.com/' + i;
request(tempurl, function(error, response, body) {
if (error) reject(error);
var $ = cheerio.load(body);
resolve($('title').text() + '\n');
});
});
};
如果我想获得前 4 个标题,我将这样链接我的 .then():
var result = '';
xkcd(1)
.then(fullfilled => {
result += fullfilled;
})
.then(() => xkcd(2))
.then(fullfilled => {
result += fullfilled;
})
.then(() => xkcd(3))
.then(fullfilled => {
result += fullfilled;
})
.then(() => xkcd(4))
.then(fullfilled => {
result += fullfilled;
console.log(result);
});
有没有更优雅的方法来做到这一点,而无需链接那么多“then”?假设我想获得前 50 个漫画标题,我将不得不链接很多“then”。
我可以在不使用 Promises 的情况下使用递归回调来做到这一点:
function getXKCD(n) {
var i = 1;
(function getURL(i){
var tempurl = 'https://www.xkcd.com/' + i;
request(tempurl, function(error, response, body) {
if (error) console.log('error: ' + error);
var $ = cheerio.load(body);
//prints the title of the xkcd comic
console.log($('title').text() + '\n');
i++;
if (i <= n) getURL(i);
});
})(i);
}
getXKCD(4);
但我很想知道我是否可以对 Promises 做同样的事情。谢谢。
最佳答案
您可以将 promise 推送到一个数组,然后返回 Promise.all
,当所有 promise 都已解决时,它将解决,类似于
function getXKCD(_start, _end) {
if (_end >= _start) return Promise.reject('Not valid!');
var promises = [];
(function rec(i) {
var p = new Promise(function(resolve, reject) {
request('https://www.xkcd.com/' + i, function(error, response, body) {
if (error !== null) return reject(error);
if (i <= _end) rec(++i);
let $ = cheerio.load(body);
resolve($('title').text());
});
});
promises.push(p);
})(_start);
return Promise.all(promises);
}
getXKCD(1, 50).then(res => { /* All done ! */ }).catch( err => { /* fail */ })
关于javascript - 在不使用多个 "then' 的情况下链接 Promise",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46087564/