【问题标题】:how to use promise with a sql request如何在 sql 请求中使用 promise
【发布时间】:2019-02-14 09:47:03
【问题描述】:

我在调用函数时调度一个动作,它应该尝试将文件/图像传递给另一个函数以将其上传到本地文件夹,一旦完成尝试插入 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));
        })
    });
  });
}

【问题讨论】:

  • 您可能会考虑在编写代码时使用一致的缩进 - 这将使阅读和调试变得更加容易,不仅对于潜在的回答者,而且对于您来说,当我们都可以看到 { } 块及其嵌套级别一目了然,而不必仔细挑选每一行来挑选逻辑路径。
  • 这个问题看起来你随后同时调用了resolvereject,没有if/elsetry/catch 将它们分开,所以它不起作用

标签: javascript react-native


【解决方案1】:

你做错了你必须这样使用

const SQLite = {
    registerDataIntoDtabase : ()=> new Promise((resolve, reject)=>{

    }),
    addPosts:()=> new Promise((resolve, reject)=>{
        // you code ... 
        SQLite.registerDataIntoDtabase( your_parameters ).then()
    }),
}

在你的情况下,函数没有被调用,是的,在你的 sql 查询中使用 try catch 从 sql 中获取一些错误

【讨论】:

  • 从您的回答中不清楚您认为 OP 做错了什么或他应该如何解决它,但看起来您建议使用 Promise constructor antipattern!
  • 他想在redux有界函数中调用这个registerDataIntoDtabase,这是不可能的,你怎么能在范围之外调用一个函数? @Bergi
【解决方案2】:

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

【讨论】:

  • 请不要只是复制包自述文件的介绍(没有正确引用和引用它),而是展示如何将库应用于问题中所述的特定问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2019-01-02
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 2021-08-12
相关资源
最近更新 更多