NodeJS 使用async函数编辑数组列表节点js

dy1byipe  于 2023-01-16  发布在  Node.js
关注(0)|答案(2)|浏览(144)

我尝试转换数组wordList的所有元素,并将它们推送到一个新列表translatedWordList,中,但是由于translate()是异步的,所以当我回调或返回它时,新列表为空

function translateWordList(wordList, callback) {
  var translatedWordList = [];

  wordList.forEach((word) => {
    translate(word, (translation) => {
      translatedWordList.push(translation);
    });
  });

  callback(translatedWordList);
}

我尝试通过使用while循环延迟回调来解决这个问题,该循环一直运行到translatedWordListwordList的长度匹配为止,但是translate函数没有记录任何内容

function translateWordList(wordList, callback) {
  var translatedWordList = [];

  wordList.forEach((word) => {
    translate(word, (translation) => {
      translatedWordList.push(translation);
      console.log(translation)
      counter++;
    });
  });

  while (translateWordList.length < wordList.length) {}
  callback(translatedWordList);
}
ztigrdn8

ztigrdn81#

不使用Array#forEach,而使用普通的for循环并使函数异步,这样就可以使用await关键字。

async function translateWordList(wordList, callback) {
  var translatedWordList = [];
  
  for(const word of wordList) {
    translatedWordList.push(await translate(word));
  }

  callback(translatedWordList);
}

如果您的translate函数不返回承诺,而只使用回调,那么您可以承诺该函数。

function translatePromise(word) {
  return new Promise((resolve, reject) => {
    translate(word, (translation, err) => {
      // assuming your callback signals an error in the second parameter
      if(err) {
        reject(err);
        return;
      }
      resolve(translation);
    });
  });
}

然后将第一个示例中的translate(word)调用替换为translatePromise(word)
然而,如果你不想使用async/await,你可以这样做。

function translateWordList(wordList, callback) {
  Promise.all(wordList.map((word) => {
    return new Promise((resolve) => {
      translate(word, resolve);
    });
  }))
  .then(callback);
}
lkaoscv7

lkaoscv72#

async function translateWordList(wordList, callback) {
    const translatedWordList = [];

    for (let i = 0; i < wordList.length; i++) {
        const word = wordList[i];
        await translate(word, (translation) => 
            translatedWordList.push(translation));
    }

    callback(translatedWordList);
}

相关问题