2016-07-19 2 views
1

SELECT 요청을 시작하기 전에 여러 개의 INSERT를 수행하고 싶습니다. 내 문제는 SELECT가 발생하면 INSERT가 아직 끝나지 않았다는 것입니다. 코르도바 SQLite는 삽입이 완료 될 때까지 대기합니다.

데이터베이스 처리를 위해 공장을 만들어 :
databaseFactory.js

factory.insertIntoTable= function (database, data) { 
    var sqlCommand = 'INSERT INTO blablabla'; 

    database.transaction(function(tx) { 
    database.executeSql(sqlCommand, [data.thingsToInsert], function (resultSet) { 
     console.log('success: insertIntoTable'); 
    }, function (error) { 
     console.log('SELECT error: ' + error.message); 
    }); 
    }, function(error) { 
    console.log('transaction error: ' + error.message); 
    database.close(); 
    }, function() { 
    console.log('transaction ok: insertIntoTable'); 
    }); 
}; 

, 삽입 어쨌든 잘 작동

ionic.Platform.ready(function() { 
    if (window.cordova && window.cordova.plugins.Keyboard) { 
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
    cordova.plugins.Keyboard.disableScroll(true); 
    }; 

    if(window.StatusBar) { 
    StatusBar.styleDefault(); 
    } 

    db = window.sqlitePlugin.openDatabase({name: 'myDbName.db', location: 'default'}); 

    if (window.Connection) { 
    if (navigator.connection.type !== Connection.NONE) { 
     databaseFactory.createTables(db); 

     MyService.getStuffFromAPI().then(function(result) { 
     for (var index = 0; index < result[0].campaigns.length; index++) { 
      databaseFactory.insertIntoTable(db, result[0].campaigns[index]); 
     } 

     var selectResult = databaseFactory.selectFromCampaigns(); 

     console.log(selectResult); //This log comes earlier than the above inserts could finish. 

     }, function(result) { 
     console.log(result); 
     }); 
    } 
    } 
}); 

app.js를, 나는 그것을 확인했다.

나는 datebase.transaction이 비동기 적이기 때문에 단일 db.executeSQL 명령으로 시도했지만 $ q resolve를 추가해도 동일한 문제가 있음을 알 수 있습니다. 덕분에 도움을받을 수있었습니다!

답변

1

문제는 자체 비동기 기능을 그리고 함수 본문의 I 내부에 있기 때문에 나는 database.transaction(function (tx){})를 사용하는 방법이었다 동기식 CRUD 작업을 수행 할 수 있으며 순서대로 수행됩니다.

ionic.Platform.ready(function() { 
    if (window.cordova && window.cordova.plugins.Keyboard) { 
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
    cordova.plugins.Keyboard.disableScroll(true); 
    }; 

    if(window.StatusBar) { 
    StatusBar.styleDefault(); 
    } 

    db = window.sqlitePlugin.openDatabase({name: 'MagicalWonder.db', location: 'default'}); 

    if (window.Connection) { 
    if (navigator.connection.type !== Connection.NONE) { 
     MyService.getMyPreciousData().then(function(result) { 

     db.transaction(function(tx) { 
      databaseFactory.createTable(tx);    

      for (var index = 0; index < result[0].campaigns.length; index++) { 
      databaseFactory.insertIntoTable(tx, result[0].myPreciousData[index]); 
      } 
      // HERE I CAN MAKE THE SELECT REQUESTS 
     }, function(error) { 
      console.log('transaction error: ' + error.message); 
      database.close(); 
     }, function() { 
      console.log('transactions successfully done.'); 
     }); 
     }, function(result) { 
     console.log(result); 
     }); 
    } 
    } 
}); 

팩토리 메소드 (고정)

factory.insertIntoTable = function (tx, data) { 
    var sqlCommand = 'INSERT INTO wanders (' + 
        'id, ' + 
        'magic_spell) values (?,?)'; 

    tx.executeSql(sqlCommand, [data.id, data.magic_spell], function (tx, resultSet) { 
     console.log('Success: insertIntoBookOfWonder'); 
    }, function (tx, error) { 
    console.log('SELECT error: ' + error.message); 
    }); 
}; 
0

모든 삽입물은 약속을 반환합니다. 이러한 약속을 일련의 약속으로 유지하고 $ q.all을 사용하여 모든 약속이 완료 될 때까지 기다리십시오.

예 : 모든 삽입의 객체

function insert(object){ 

    var deferred = $q.defer(); //IMPORTANT 

    var query = "INSERT INTO objectTable (attr1, attr2) VALUES (?,?)"; 
    $cordovaSQLite.execute(db, query, [object.attr1, object.attr2]).then(function(res) { //db object is the result of the openDB method 
     console.log("INSERT ID -> " + res.insertId); 
     deferred.resolve(res); //"return" res in the success method 
    }, function (err) { 
     console.error(JSON.stringify(err)); 
     deferred.reject(err); //"return" the error in the error method 
    }); 

    return deferred.promise; //the function returns the promise to wait for 
} 

그리고 다음을 삽입하는 데 사용 공장에있어서,

promises.push(yourService.insert(obj).then(function(result){ //"result" --> deferred.resolve(res); 
    //success code 
}, function(error){ //"error" --> deferred.reject(err); 
    //error code 
})); 

그리고 마지막으로 :

$q.all(promises).then(function(){//do your selects}, function(err){//error!}); 

그것이 도움이되기를 바랍니다.

더 $의 Q에 대한 정보와 $ q.all : https://docs.angularjs.org/api/ng/service/$q#all

그리고 또 다른 예 : https://www.jonathanfielding.com/combining-promises-angular/

+0

'$의 q.all (약속)도'반환 약속 (고정)
app.js. 그래서 당신은 다음과 같은 것을 할 필요가 있습니다 :'$ q.all (promise) .then (function() {// 성공하면 코드를 선택 하시겠습니까?}, function (err) {// 오류시 코드})' . –

+0

그래,이 방법을 수정하고 여전히 작동하지 않습니다. API 요청이 $ q가 아니기 때문에 $ q가 완료되었는지 여부를 알 수 없습니다. SQLite 플러그인을 사용해 보셨습니까? – MagicDragon

+0

나는 결국 해결책을 찾은 것 같아. – MagicDragon

관련 문제