简体   繁体   中英

What is the purpose of spread function in this code?

I am trying to figure out how to use mysql-promise. https://www.npmjs.com/package/mysql-promise

Here is some sample code;

var db = require('mysql-promise')();

db.configure({
    "host": "localhost",
    "user": "foo",
    "password": "bar",
    "database": "db"
});

db.query('UPDATE foo SET key = ?', ['value']).then(function () {
    return db.query('SELECT * FROM foo');
}).spread(function (rows) { //what's purpose of spread()?
    console.log('Loook at all the foo', rows);
});

What is the purpose of the spread function? What exactly does it do?

Jaromanda X is correct, the example misrepresents spread .

Ideal use case for spread is when your callback/ chained function expects multiple parameters, but a promise returns a single value ( our job to make sure that it is array of parameters in format used by chained function), so:

Promise.resolve([1,2,3]).spread(function(a, b, c){  ...

is equivalent to ( in ES6):

Promise.resolve([1,2,3]).then( ([a, b, c]) => {  ...

.spread is a Bluebird (the promise library that `mysql-promise is using) function.

Basically, .spread allows you to handle a return value from the promise that is an array instead of a single value.

See http://bluebirdjs.com/docs/api/spread.html for more information.

The spread function comes from the Bluebird promises library that comes with the mysql-promise library. It unwraps a promise that must return an array and gives each element of that array to the function passed to it, in this case the rows from the mysql database.

From mysql-promise's package.json on github:

 "dependencies": {
    "bluebird": "^2.10.2",
    "mysql": "^2.10.2"
  },

Here is more info from the bluebird project: http://bluebirdjs.com/docs/api/spread.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM