Using Normal Promise Syntax
Chain Promises
You can chain your promises if you want them sequential:
get('a.json').then(function(a) {
return get('b.json');
}).then(function(b){
return get('c.json');
}).then(function(c) {
// all done here
}), function(err) {
// error here
});
Or in ES7, you can use async/await
like this:
async function someFunction() {
let a = await get('a.json');
let b = await get('b.json');
// do something with a and b here
return something;
}
someFunction().then(result => {
// all done here
}).catch(err => {
// error here
});
Run Promises in Parallel
If you want them loaded in parallel, you can use Promise.all()
:
Promise.all([get('a.json'), get('b.json'), get('c.json')]).then(function(results) {
// all done with results here
}, function(err) {
// error here
});
Sequence Using .reduce()
Or, if you use the same code to process each result, you can load them sequentially using the reduce()
design pattern:
['a.json', 'b.json', 'c.json'].reduce(function(p, item) {
return p.then(function(){
// process item here
});
}, Promise.resolve()).then(function(result) {
// all done here
}, function(err) {
// error here
});
Sequence Using Bluebird's .map()
Or, if using the Bluebird promise library, it has Promise.map()
which is very useful for parallel operations on an array
Promise.map(['a.json', 'b.json', 'c.json'], function(item) {
// do some operation on item and return data or a promise
return something;
}).then(function(results) {
// all done
}, function(err) {
// error here
});
Making get(x).get(y).get(z)
Work
Extending the Promise
I was intrigued by the get(x).get(y).get(z)
question using promises. I conjured up a way to do that in this working snippet:
function get(url) {
function pget(u) {
var p = this.then(function (result) {
log(result);
return get(u);
});
p.get = pget;
return p;
}
var p = new Promise(function (resolve, reject) {
setTimeout(function() {
resolve(url);
}, 500);
});
p.get = pget;
return p;
}
get('a.json').get('b.json').get('c.json').then(function(result) {
log(result);
log("done");
}, function(err) {
log("err");
});
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…