設想你有一個工具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