I Can't Return A Object In .then() Promise
I created an object of ids, however I can not access it outside of my for or in my next .then (), i make det as global variable, does anyone know where it is wrong? .then(function(
Solution 1:
Assuming you use this node mysql package you can get the inserted id from the result of the insert statement.
Since that package does not seem to be aware of the existence of promises you can dust off the api with a wrapper that will return a promise:
//turn an insert query with callback function // into a function returning a promiseconstinsertAsPromise = connection => args =>newPromise(
(resolve,reject)=>//call connection query with variable amount of argument(s)// using Function.prototype.apply
connection.query.apply(connection,args.concat(
//add the callback to the list of arguments, callback// is the last argument(error, results, fields) =>
(error)
? reject(error)
: resolve([results,fields])
))
);
const sqlEdit = "INSERT INTO images_det SET ?";
Promise.all(
object.det_img.map(
image=>//map magical/global object.det_img to promiseinsertAsPromise(connection)([sqlEdit,image.name_img])
.then(//when promise resolves get the inserted id([results,fields])=>
results.insertId
)
)
)
.then(
results=>console.log(results)//should log an array of id's
)
.catch(
err=>console.error("something went wrong:",err)
)
Post a Comment for "I Can't Return A Object In .then() Promise"