【问题标题】:WinJS return in promise arrayWinJS 在 promise 数组中返回
【发布时间】:2013-12-15 13:32:44
【问题描述】:

我在 Winjs 承诺中返回数组时遇到问题,我不知道我的代码有什么问题。当我创建一个承诺并执行 .done 或 .then 时,我的承诺什么也不做。

代码:

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++);
            });

如有任何建议,我将不胜感激。

【问题讨论】:

  • 嗯,这不是你创建承诺的方式。 new WinJS.Promise 的函数参数采用三个参数,传统上命名为 cep。产生结果后调用c(result)

标签: javascript windows-8 microsoft-metro winjs


【解决方案1】:

我假设您不想立即返回,而是希望在数组充满元素后返回?

我认为你想编写更像这样的代码:

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;
         });
}

【讨论】:

  • 谢谢 :) 这很明显,有时我不认为 ;) 谢谢!
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2017-09-25
  • 2022-01-20
  • 2018-12-05
  • 1970-01-01
相关资源
最近更新 更多