Search code examples
javascriptmysqlnode.jspromisenode-mysql

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?


Solution

  • 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]) => {  ...