首页 > 解决方案 > 如何在 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));
        })
    });
  });
}

标签: javascriptreact-native

解决方案


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


推荐阅读