javascript - 如何在 sql 请求中使用 promise
问题描述
我在调用函数时调度一个动作,它应该尝试将文件/图像传递给另一个函数,以便在完成后将其上传到本地文件夹尝试插入 sqlite 数据库,以确保这些步骤将通过一,我使用过Promises,我的问题是图像上传到本地文件夹但插入数据库失败,请帮助找到如何正确完成插入数据库。
这是我的代码:
export const addPosts = ( imageName , data,title,categ,idSubCateg) => {
const idSubCat = idSubCateg ? idSubCateg : 0;
return (dispatch) => {
dispatch({ type: ADDING_POST });
new Promise((resolve, reject) => {
uploadImage(imageName, data) // this for upload image to local folder
const postToSave = { title, imageName };
resolve(registerDataIntoDtabase(dispatch,imageName,title,categ,idSubCat));
reject(handleError(dispatch, 'an Error Occured'));
});
}
}
const registerDataIntoDtabase = (dispatch,title,imagenmae,categ,idSubCat) => {
//insert into database
new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql('INSERT INTO rooms (room,idHouse,title,idOwner) VALUES (?,?,?,?)', [imagenmae,categ,title,idSubCat], (tx, results) => {
resolve(dispatch({ type: ADDING_SUCCESS }));
reject(handleError(dispatch, error.message));
})
});
});
}
解决方案
Promise-mysql 是 mysqljs/mysql 的包装器,它使用 Bluebird Promise 包装函数调用。通常这将使用 Bluebird 的 .promisifyAll() 方法来完成,但 mysqljs/mysql 的足迹与 Bluebird 所期望的不同。
要安装 promise-mysql,请使用 npm:
$ npm install promise-mysql 有关如何使用 mysql 函数的文档,请参阅 mysqljs/mysql,有关 Bluebird 的 Promise 的文档,请参阅 Bluebird
目前仅支持标准连接(使用 .createConnection())和池(使用 .createPool())。createPoolCluster 尚未实现。欲了解更多信息,请访问https://www.npmjs.com/package/promise-mysql
推荐阅读
- java - 单击不同的按钮时如何播放多个WAV文件?
- c++ - OBS显示绘制透明背景
- c# - Azure Front Door 不在浏览器中维护自定义域
- c++ - 我可以将 cocos 项目导入 Unreal 4 吗?
- regex - 正则表达式检查字符串是否以字母开头并且不包含子字符串
- visual-studio-code - 将 VSCode 元素颜色名称与屏幕位置相关联
- tensorflow - ai-platform:使用 Estimators 运行 TensorFlow 2.1 训练作业时,输出中没有 eval 文件夹或导出文件夹
- typescript - 如何在以枚举为返回类型的函数中从开关盒返回字符串值而不是键?
- vue.js - 组件如何调用 Vue.js 插槽中定义的组件的方法?
- javascript - 询问有关如何在脚本中创建 php 的问题?