JSON 数组未定义且在 promise Bluebird 中为空

JSON array undefined & empty in promise Bluebird

我正在使用 Promise bluebird 处理来自文件的 json 数组对象。如果我想将数据存储在 json 数组(称为列表)中,并在最终过程中将其存储在 return 中,就会出现问题。 该列表在列表的return之后甚至在最后的过程中empty/undefined。 运行 代码,我总是有 1 个不为 false 的值触发列表中 json 的 adding/push。

你能帮我解决这个问题吗?你会在下面找到我的代码。

提前致谢!!!

var Promise = require('bluebird');
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));

fs.readdirAsync(dir).map(function (filename) {
    return fs.readFileAsync(dir + "/" + filename, "utf8");
}).then(function(result){
    var list=[];

    result.map(function(row, index){
      Promise.coroutine(function*() {
        update(row, index).then(function(value){
          if (value!=false){
            var trade_update = new updated_Item(row.ID, row.Quantity, row.Price, row.Remark);
            list.push(trade_update);
            console.log(JSON.stringify(list));          <-- This works. It gives me data
          }
          return list;
        })
      })();
    });
    console.log('list: ' + JSON.stringify(list));        <-- output:    list:[]
    return list;
}).finally(function(result){
  console.log('Final outcome: '+ ' ' + JSON.stringify(result));      <-- output: Final outcome: undefined
})

在 Samuel 的帮助下,我的代码现在是:

var Promise = require('bluebird');
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));


function updateOrder(done){
  fs.readdirAsync(dir).map(function (filename) {
      return fs.readFileAsync(dir + "/" + filename, "utf8");
  }).then(function(result){
    var list=[];

    result.map(function(row, index){
      Promise.coroutine(function*() {
        update(row, index).then(function(value){
          if (value!=false){
            var trade_update = new updated_Item(row.ID, row.Quantity, row.Price, row.Remark);
            list.push(trade_update);
            done(list);      
          }
        })
      })();
    });

    //done(list);   <--if I put the done callback here, it will give me an empty list. I though once the result.map finished processing all the values give me the end result.
  }
}

updateOrder(function(resultList){
  console.log('List' + JSON.stringify(resultList));
})

每次更新(推送)列表时,这段代码都会给我整个结果列表。

一旦函数 updateOrder 完成,我会在最后收到结果列表。

如评论中所述。 Promise.coroutine 是异步的,所以这意味着结果不会在您的代码到达后立即得到 return。这几乎可以解释您看到的现象,您在代码中得到的后面的打印语句表明 list 未定义。

你可以做的是将你到达那里的整个代码包装在一个函数中,然后添加一个 callback 函数作为 async 函数的参数,以便在它完成任务时调用,一起 return 将填充的列表返回以供以后处理。

我已经为你的案例写了一个伪代码,不幸的是我无法在我的 IDE 上测试它,但概念是存在的,它应该可以工作。

考虑我的伪代码:

var Promise = require('bluebird');
var join = Promise.join;
var fs = Promise.promisifyAll(require("fs"));

// Wrap everything you got into a function with a `done` parameter (callback fn)
function doStuff(done) {
  fs.readdirAsync(dir).map(function (filename) {
    return fs.readFileAsync(dir + "/" + filename, "utf8");
  }).then(function(result){
    var list=[];

    result.map(function(row, index){
      Promise.coroutine(function*() {
        update(row, index).then(function(value){
          if (value!=false){
            var trade_update = new updated_Item(row.ID, row.Quantity, row.Price, row.Remark);
            list.push(trade_update);
          }
          done(list);
        })
      })();
    });
  }).finally(function(result){
    console.log('File read finish, but this doesnt mean I have finished doing everything!');
  })
}

// call your function and provide a callback function for the async method to call 
doStuff(function(resultList) {
  console.log('list: ' + JSON.stringify(resultList));
  // Continue processing the list data.
});