我无法在 .then() Promise 中返回对象 [英] I can't return a object in .then() Promise
本文介绍了我无法在 .then() Promise 中返回对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个 ids 对象,但是我无法在 for 之外或在我的下一个 .then () 之外访问它,我将 det 作为全局变量,有谁知道它错在哪里?
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(idHome){
home_id = idHome;
var detname_img = [];
var sqlEdit = "INSERT INTO images_det SET ?";
for(var k = 0; k < object.det_img.length; k++){
detname_img.push({
name_img : object.det_img[k].name_img,
});
connection.query(sqlEdit,detname_img[k]);
}
// console.log(detname_img);
for(var i = 0; i < detname_img.length; i++){
var getDet = ("SELECT det_id from images_det where name_img = '" + detname_img[i].name_img + " ' order by 1 desc limit 1");
connection.query(getDet, function(erro, result){
for(var k = 0; k < result.length; k++){
det.push({
det_id : result[k].det_id
});
console.log(chalk.blue(det[0].det_id));
return det;
}
});
}
});
推荐答案
假设你使用 this 节点mysql 包,您可以从 result<中获取插入的 id插入语句的/a>.
Assuming you use this node mysql package you can get the inserted id from the result of the insert statement.
由于该包似乎不知道承诺的存在,因此您可以使用将返回承诺的包装器清除 api:
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 promise
const insertAsPromise = connection => args =>
new Promise(
(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 promise
insertAsPromise(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)
)
这篇关于我无法在 .then() Promise 中返回对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文