我在 Winjs Promise 中返回数组时遇到问题,我不知道我的代码出了什么问题。当我创建一个 promise 并执行 .done 或 .then 时,我的 promise 什么也不做。
代码:
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++);
});
我将非常感谢任何建议。
最佳答案
我假设您不想立即返回,而是希望在数组充满元素后返回该数组?
我认为你想编写更像这样的代码:
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;
});
}
关于javascript - WinJS 在 Promise 数组中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20595102/