我有以下 promise 的功能:
const ajaxRequest = (url) => {
return new Promise(function(resolve, reject) {
axios.get(url)
.then((response) => {
//console.log(response);
resolve(response);
})
.catch((error) => {
//console.log(error);
reject();
});
});
}
const xmlParser = (xml) => {
let { data } = xml;
return new Promise(function(resolve, reject) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(data,"text/xml");
if (xmlDoc.getElementsByTagName("AdTitle").length > 0) {
let string = xmlDoc.getElementsByTagName("AdTitle")[0].childNodes[0].nodeValue;
resolve(string);
} else {
reject();
}
});
}
我正在尝试为 JSON 数组中的每个对象应用这些函数:
const array = [{"id": 1, "url": "www.link1.com"}, {"id": 1, "url": "www.link2.com"}]
我想出了以下解决方案:
function example() {
_.forEach(array, function(value) {
ajaxRequest(value.url)
.then(response => {
xmlParser(response)
.catch(err => {
console.log(err);
});
});
}
}
我想知道这个解决方案是否可以接受两件事:
在以下事项中对 promises 应用 forEach() 是一种好的做法吗?
是否有更好的方法将先前的 promise 结果作为参数传递到 then() 链中? (我正在传递
response
参数)。
最佳答案
您可以使用 .reduce()
访问之前的 Promise
。
function example() {
return array.reduce((promise, value) =>
// `prev` is either initial `Promise` value or previous `Promise` value
promise.then(prev =>
ajaxRequest(value.url).then(response => xmlParser(response))
)
, Promise.resolve())
}
// though note, no value is passed to `reject()` at `Promise` constructor calls
example().catch(err => console.log(err));
注意,在 ajaxRequest
函数中不需要 Promise
构造函数。
const ajaxRequest = (url) =>
axios.get(url)
.then((response) => {
//console.log(response);
return response;
})
.catch((error) => {
//console.log(error);
});
关于javascript - 将 forEach() 与 promise 一起使用,同时在 .then() 链中访问先前的 promise 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45296475/