2013-12-15 114 views
0

我有一個Winjs承諾返回數組的問題,我不知道我的代碼有什麼問題。當我創造一個承諾,並做.done或。然後我的諾言什麼都不做。WinJS返回承諾數組

代碼:

function getSth(array) { 

    return new WinJS.Promise(function() { 
     var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\_db.sqlite'; 

     var i = 0; 
     SQLite3JS.openAsync(dbPath) 
       .then(function (db) { 
        console.log('DB opened'); 
        return db.eachAsync('SELECT * FROM sthh;', function (row) { 
         array[i++] = row.sth; 
         console.log('Get a ' + row.sth); 
        }); 
       }) 
      .then(function (db) { 
       console.log('close the db'); 
       db.close(); 
      }).then(function() { 
       return array; 
      }); 
     return array; 
    }) 
} 

而在其他文件中我只是做這樣的事情:

var array = []; 
      var z = getSth(array).then(function() { 
       console.log("AAA"); 
for (var i = 0; i < array.length; console.log("#" + array[i]), i++); 
      }); 

我會爲任何建議非常gratefull。

+1

嗯,這不是你如何創建一個承諾。 'new WinJS.Promise'的函數參數有三個參數,傳統上命名爲'c','e'和'p'。當你產生結果時你可以調用'c(result)'。 –

回答

2

我假設你不想立即返回,而是想在數組元素滿之後返回數組?

我想你想編寫代碼,更像是這樣的:

function getSth(array) { 

    var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\_db.sqlite'; 

    var i = 0; 
    return SQLite3JS.openAsync(dbPath) 
      .then(function (db) { 
       console.log('DB opened'); 
       return db.eachAsync('SELECT * FROM sthh;', function (row) { 
        array[i++] = row.sth; 
        console.log('Get a ' + row.sth); 
       }); 
      }) 
     .then(function (db) { 
      console.log('close the db'); 
      db.close(); 
     }).then(function() { 
      return array; 
     }); 
} 
+0

謝謝:)這很明顯,有時我不認爲;)謝謝! – pkruk