Javascript 承诺数组中的WinJS返回
我在Winjs promise中返回数组时遇到问题,我不知道我的代码出了什么问题。当我创造一个承诺,然后去做。完成或。那么我的承诺什么都不做 代码:Javascript 承诺数组中的WinJS返回,javascript,windows-8,microsoft-metro,winjs,Javascript,Windows 8,Microsoft Metro,Winjs,我在Winjs promise中返回数组时遇到问题,我不知道我的代码出了什么问题。当我创造一个承诺,然后去做。完成或。那么我的承诺什么都不做 代码: function getSth(array) { return new WinJS.Promise(function () { var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\_db.sqlite'; v
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++);
});
var数组=[];
var z=getSth(数组).then(函数(){
控制台日志(“AAA”);
对于(var i=0;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;
});
}
嗯,这不是你做出承诺的方式。
new WinJS.Promise
的函数参数采用三个参数,传统上称为c
、e
和p
。当你产生一个结果时,你可以调用c(result)
。谢谢:)有时候我不认为这很明显;)非常感谢。