我有一个类似数组的结构,它公开了异步方法。异步方法调用返回数组结构,该结构又公开更多的异步方法。我正在创建另一个JSON对象来存储从这个结构中获得的值,因此我需要小心跟踪回调中的引用。
我已经编写了一个暴力解决方案,但我想学习一个更惯用或更干净的解决方案。
以下是一些部分代码-
var jsonItems = [];
items.forEach(function(item){
var jsonItem = {};
jsonItem.name = item.name;
item.getThings().then(function(things){
// or Promise.all(allItemGetThingCalls, function(things){
things.forEach(function(thing, index){
jsonItems[index].thingName = thing.name;
if(thing.type === 'file'){
thing.getFile().then(function(file){ //or promise.all?
jsonItems[index].filesize = file.getSize();
发布于 2015-07-15 02:27:02
它非常简单,有一些简单的规则:
你在一个承诺中创建一个承诺并返回它**-任何你没有返回的承诺都不会被等待,你创建了多个承诺,这样它就会等待所有的承诺,并且没有任何错误来自其中任何一个是silenced.
.all
silenced.
then
**s, 您通常可以在中间返回**- promise链通常最多为1级deep.
还有一些小贴士:
使用
.map
比使用 map
更好-如果你用一个函数映射值,让你简洁地表达一个接一个地应用动作的概念,如果它是空闲的,聚合比顺序执行更好--并发执行并等待它们,而不是一个接一个地执行-每个都在下一个之前等待。好了,让我们开始吧:
var items = [1, 2, 3, 4, 5];
var fn = function asyncMultiplyBy2(v){ // sample async action
return new Promise(resolve => setTimeout(() => resolve(v * 2), 100));
};
// map over forEach since it returns
var actions = items.map(fn); // run the function over all items
// we now have a promises array and we want to wait for it
var results = Promise.all(actions); // pass array of promises
results.then(data => // or just .then(console.log)
console.log(data) // [2, 4, 6, 8, 10]
);
// we can nest this of course, as I said, `then` chains:
var res2 = Promise.all([1, 2, 3, 4, 5].map(fn)).then(
data => Promise.all(data.map(fn))
).then(function(data){
// the next `then` is executed after the promise has returned from the previous
// `then` fulfilled, in this case it's an aggregate promise because of
// the `.all`
return Promise.all(data.map(fn));
}).then(function(data){
// just for good measure
return Promise.all(data.map(fn));
});
// now to get the results:
res2.then(function(data){
console.log(data); // [16, 32, 48, 64, 80]
});
发布于 2017-01-22 20:57:32
下面是一个使用reduce的简单示例。它以串行方式运行,保持插入顺序,并且不需要Bluebird。
/**
*
* @param items An array of items.
* @param fn A function that accepts an item from the array and returns a promise.
* @returns {Promise}
*/
function forEachPromise(items, fn) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item);
});
}, Promise.resolve());
}
并像这样使用它:
var items = ['a', 'b', 'c'];
function logItem(item) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
resolve();
})
});
}
forEachPromise(items, logItem).then(() => {
console.log('done');
});
我们发现向循环中发送一个可选的上下文是很有用的。上下文是可选的,并由所有小版本共享。
function forEachPromise(items, fn, context) {
return items.reduce(function (promise, item) {
return promise.then(function () {
return fn(item, context);
});
}, Promise.resolve());
}
您的promise函数将如下所示:
function logItem(item, context) {
return new Promise((resolve, reject) => {
process.nextTick(() => {
console.log(item);
context.itemCount++;
resolve();
})
});
}
发布于 2017-06-24 06:18:20
我也经历过同样的情况。我使用两个Promise.All()解决了这个问题。
我认为这是一个非常好的解决方案,所以我在npm:https://www.npmjs.com/package/promise-foreach上发布了它。
我认为你的代码应该是这样的
var promiseForeach = require('promise-foreach')
var jsonItems = [];
promiseForeach.each(jsonItems,
[function (jsonItems){
return new Promise(function(resolve, reject){
if(jsonItems.type === 'file'){
jsonItems.getFile().then(function(file){ //or promise.all?
resolve(file.getSize())
})
}
})
}],
function (result, current) {
return {
type: current.type,
size: jsonItems.result[0]
}
},
function (err, newList) {
if (err) {
console.error(err)
return;
}
console.log('new jsonItems : ', newList)
})
https://stackoverflow.com/questions/31413749
复制相似问题