Javascript - 等待数组完成填充

时间:2018-06-03 23:01:25

标签: javascript arrays asynchronous

我试图获取一些数组元素的值。它适用于元素[0],[1],[2],[3],但不适用于[4]。

function getBase64() {
  const urls = ['https://i.imgur.com/egNg7JU.jpg',
    'https://i.imgur.com/RLZ7WH1.jpg', 'https://i.imgur.com/qfabBbA.jpg',
    'https://i.imgur.com/Zuh1KaX.jpg', 'https://i.imgur.com/yD7X6Q1.jpg'
  ];

  let base64urls = [];

  const start = async () => {
    await asyncForEach(urls, async (num) => {
      await waitFor(50)
      toDataURL(num, function(dataURL) {
        base64urls.push(dataURL);
      });
    })
    console.log(base64urls);
    console.log(base64urls[4]);
  }
  start()

}

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array)
  }
}

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))

toDataURL只返回图像的base64值。每当我尝试console.log(base64urls[4])时,它都会返回&#39; undefined&#39;。我确实得到了前面元素的正确值。有没有办法重构这个,或者在检查其元素的值之前使用另一种等待数组完全填充的方法?

修改

这是我的toDataURL

function toDataURL(src, callback) {
  const image = new Image();
  image.crossOrigin = 'Anonymous';

  image.onload = function () {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.height = this.naturalHeight;
    canvas.width = this.naturalWidth;
    context.drawImage(this, 0, 0);
    const dataURL = canvas.toDataURL('image/jpeg');
    callback(dataURL);
  };

  image.src = src;
}

2 个答案:

答案 0 :(得分:4)

看起来my_dictionary = {} # dictionary to store word and meaning user_word = input("Enter word: ").lower() # .lower() for not being case sensitive user_meaning = input("Enter Meaning: ").lower() # .lower() # add word and meaning to dictionary my_dictionary[user_word] = user_meaning # search word user_search = input("What word/phrase would you like to search: ").lower() print("Meaning of {0} is: {1}".format(user_search, my_dictionary[user_search])) 是异步的并且基于回调 - 要么更改它以便它返回toDataURLPromise await,要么传递{{1}将Promise放入回调中:

Promise

如果您想更改resolve函数以返回Promise,那么您不必将其视为回调:

async function getBase64() {
  const urls = ['https://i.imgur.com/egNg7JU.jpg', 
                'https://i.imgur.com/RLZ7WH1.jpg', 'https://i.imgur.com/qfabBbA.jpg', 
                'https://i.imgur.com/Zuh1KaX.jpg', 'https://i.imgur.com/yD7X6Q1.jpg'];
  const base64urls = [];
  for (const url of urls) {
    const dataURL = await new Promise(resolve => toDataURL(url, resolve));
    base64urls.push(dataURL);
  }
  console.log(base64urls);
  console.log(base64urls[4]);
}

然后toDataURL

答案 1 :(得分:2)

您可以在此类情况下使用promise.all等待查询结果

&#13;
&#13;
const urls = ['https://i.imgur.com/egNg7JU.jpg', 
'https://i.imgur.com/RLZ7WH1.jpg', 'https://i.imgur.com/qfabBbA.jpg', 
'https://i.imgur.com/Zuh1KaX.jpg', 'https://i.imgur.com/yD7X6Q1.jpg'];

let base64urls = [];
 
Promise.all(urls.map(url => fetch(url))).then(res => toBase64DataURL(res)).then(result => {base64urls.push(result.toDataURL());
console.log(base64urls);});

function toBase64DataURL(src) {
  return new Promise(resolve => {
const image = new Image();
image.crossOrigin = 'Anonymous';

image.onload =  _=> {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  canvas.height = this.naturalHeight;
  canvas.width = this.naturalWidth;
  context.drawImage(this, 0, 0);
  const dataURL = canvas.toDataURL('image/jpeg');
  resolve(dataURL);
};
image.src = src;
  });
}
  
&#13;
&#13;
&#13;