等待回调的异步功能

时间:2017-05-10 13:30:21

标签: javascript typescript asynchronous

我有一个带有回调函数的包模块的异步方法。该方法本身返回undefined。

我对异步编码很新,并希望能够暂停程序的执行,直到从回调方法为变量arrayWithData分配数据。

e.g。

let dataFiles = fs.etc   

function makeDataArray(dataFiles) {
   let arrayWithData = [];
   for (let dataFile in dataFiles) {
     package.magicMethodToParseData(dataFile, function(result){ //async method with callback
        arrayWithData.push(result) //happens later
     });
   }
   return arrayWithData; //This returns undefined
}

function doSomethingWithData(dataArray) {
   /* Doing Stuff with Data Array */
}

/* Broken Code with undefined */
doSomethingWithData( makeDataArray(dataFiles) );

我知道我可以在回调函数中添加其余的执行但是要避免这种情况并保持代码平稳。

如何等待数据分配到阵列然后继续执行?

更新:添加了github测试项目以展示完整的问题,因为承诺一直被拒绝。 Github链接:https://github.com/Jonathan002/autofont.git

2 个答案:

答案 0 :(得分:1)

您可以使用Promise.all返回包含数组的PromisePromise.all的参数必须是一个promises数组,它返回一个值数组的promise。

你可以像这样使用它:

function makeDataArray(dataFiles) {
  return Promise.all(dataFiles.map(function (dataFile) {
    return new Promise(function (resolve, reject) {
      package.magicMethodToParseData(dataFile, function (error, result) {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      });
    });
  }));
}

makeDataArray(dataFiles)
  .then(doSomethingWithData)
  .catch(console.error);

答案 1 :(得分:0)

嗨Jonathan这是一个非常常见的异步编程方案。您可以使用es6的本机承诺或我们的承诺库,如bluebird或q。 这是一个代码示例

   function someAsyncFunction() {
       // return promise here 
   }

  const promiseArray = [];

  // some random loop 
  for(let i = 0; i < 5; i++) {
  promiseArray.push(someAsyncFunction());

}
 Promise.all(promiseArray).then((results)=> {
 // resolved promises
console.log(results);
}).catch((error) => {
  console.log('errors ', errors);
})

如果您需要很好地理解promises如何工作,您可以阅读MDN上的Promise文档

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise