设想你有一个工具foo,它可以异步产生两个值(x和y):
function getY(x) {return new Promise( function(resolve, reject) {setTimeout( function() {resolve( (3*x) -1 );}, 100);});
}function foo(bar, baz) {var x = bar * baz;return getY(x).then( function(y){return [x, y];});
}foo(10, 20)
.then(function (msgs) {var x = msg[0];var y = msg[1];console.log(x, y);
});// getY:延迟0.1秒返回一个Promise对象,值为 3*x-1;
// foo:在等待getY()执行完毕后,返回一个Promise数组
你可能注意到,上述的方法可以用Promise.all来完成:
function foo(bar, baz){var x = bar * baz;return [Promise.resolve(x),getY(X)];
}
Promise.all(foo(10, 20)
)
.then(function (msgs){var x = msgs[0];var y = msgs[1];console.log(x,y);
});// 代码变得简洁,逻辑更清晰了..
可以看到Promise.all的then里面有一个var x = msgs[0], var y = msgs[1]…这个操作的开销有点大…
// by Reginald Braithwaite
function spread(fn) {return Function.apply.bind(fn, null);
}Promise.all(foo(10, 20)
)
.then(spread(function (x, y){console.log(x, y);})
)
可以进一步的将spread放入then中
Promise.all(foo(10, 20)
)
.then( Function.apply.bind(function(x, y){console.log(x, y);},null)
);
诶,回归主题,使用ES6的解构
Promise.all(foo(10, 20)
)
.then(function(msgs) {var [x, y] = msgs;console.log(x, y);
});
将解构应用到函数的参数中
Promise.all(foo(10, 20)
)
.then(function ([x, y]){console.log(x, y);
});
// 注:解构赋值,一定要好好学,可以简化你的代码,使逻辑更加清晰...
参考《你不知道的JavaScript》(中卷)P223~P225