Home > OS >  using async function to edit an array list node js
using async function to edit an array list node js

Time:01-16

I'm trying to translate all elements of the array wordList and pushing them to a new list translatedWordList, but because translate() is async the new list is empty when I callback or return it

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

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

  callback(translatedWordList);
}

I tried to solve this by delaying the callback using a while loop that runs until the length of translatedWordList and wordList match, but the function translate is not logging anything

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

CodePudding user response:

Instead of using a Array#forEach, just use a normal for loop and make your function async so you can use the await keyword.

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

  callback(translatedWordList);
}

If your translate function does not return a promise and only uses a callback, then you can promisify that function.

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

Then replace the translate(word) call in the first example with translatePromise(word).

However, if you don't want to work with async/await you could do something like this.

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

CodePudding user response:

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