所以承诺对我来说是相当新的,但我喜欢这个主意。
我以前使用过这个,它只是在完全读取文件并按预期工作后才返回数据:
function something{
for (var i = 0; i < files.length; i++) {
//push to the array
promises.push(readFile(files[i]));
}
//use reduce to create a chain in the order of the promise array
promises.reduce(function (cur, next) {
return cur.then(next);
}, Promise.resolve()).then(function () {
//all files read and executed!
}).catch(function (error) {
//handle potential error
});
}
function readFile(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function (progressEvent) {
loadGeoJsonString(progressEvent.target.result, file.name);
resolve();
}
reader.onerror = function (error) {
reject(error);
}
reader.readAsText(file);
});
}
我想通过使用&#34;然后&#34;来重做这个。和&#34; .catch&#34;处理成功和不成功。在我目前的解决方案(谷歌地图API澄清,但无关紧要)我想承诺一个函数,而不返回原始函数中的承诺。这就是我所拥有的:
//create infobox object on marker
function createInfobox(lat, lng) {
var pos = new G.LatLng(lat, lng);
promiseThis(dropMarker, pos, 'drop marker')
.then(promiseThis(getGeocodeResult, pos, 'get address'))
.catch(reason => {alert(reason)})
.then(promiseThis(isDeliverable, pos, 'determine deliverable status'))
.catch(reason => {alert(reason)})
.then(promiseThis(getStores, pos, 'find stores'))
.catch(reason => {alert(reason)});
}
//handle promises
function promiseThis(doThis, withThis, task) {
return new Promise(function (resolve, reject) {
var result = doThis(withThis);
if (result) {
resolve(result);
} else {
reject('Unable to ' + task);
}
});
}
//drop marker on location
function dropMarker(location) {..} //return object
//get geocode results
function getGeocodeResult(latlng) {..} //return string
最后,我想保留数组中每个promise的结果,稍后再使用它。目前,getGeocodeResult只返回“无法获取地址”#39;立即(也作为控制台错误,而不是警报)
我需要了解哪些承诺才能使其发挥作用?
答案 0 :(得分:3)
如果您的用例是使用promise包装函数执行(以捕获错误),您可以执行类似下面的代码。
您只需要1 catch
个函数来处理整个链中的错误。尝试删除评论并查看其行为。
另请参阅promisify
函数,该函数在我看来提供了更好的API。
function promiseThis(doThis, withThis, task) {
return new Promise((resolve, reject) => {
const result = doThis(withThis);
if (result) {
resolve(result)
} else {
reject(`can't do task: ${task}`)
}
})
}
function print(name) {
// throw Error('printing error!');
console.log(name);
return name;
}
function capitalizeName(name) {
// throw Error('error capitalizing?!');
return name.toUpperCase();
}
fetch('https://randomuser.me/api/')
.then(response => response.json())
.then(json => promiseThis(print, json.results[0].email))
.then(email => promiseThis(capitalizeName, email))
.then(email => promiseThis(print, email))
.then(() => promiseThis(print, 'I can ignore the incoming value'))
.catch(e => console.error(e))
// You can achieve a nicer API like this
function getEmail(json) {
return json.results[0].email
}
function promisify(f, ...args) {
return function(resolved) {
return new Promise((resolve, reject) => {
resolve(f.apply(null, [...args, resolved]))
})
}
}
fetch('https://randomuser.me/api/')
.then(response => response.json())
.then(promisify(getEmail))
.then(promisify(print))
.then(promisify(capitalizeName))
.then(promisify(print))
.then(promisify(print, 'I can ignore the incoming value'))
.catch(e => console.error(e))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;