Skip to content

Instantly share code, notes, and snippets.

@goish135
Last active December 10, 2021 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goish135/aa4b894ec05b887b7bbd6ca5dfda0876 to your computer and use it in GitHub Desktop.
Save goish135/aa4b894ec05b887b7bbd6ca5dfda0876 to your computer and use it in GitHub Desktop.
const forLoop = async _ => {
console.log('start');
for (let index = 0; index < fruitsToGet.length; index ++) {
const fruit = fruitsToGet[index];
const numFruit = await getNumFruit(fruit);
console.log(numFruit);
}
console.log('End')
}
/*
“Start”;
“Apple: 27”;
“Grape: 0”;
“Pear: 14”;
“End”;
*/

如何在 JS 迴圈中正確使用 async 與 await https://iter01.com/425093.html?fbclid=IwAR1z_PziknxZiMxYEtIcrZy81MixQQ1zktADMod2awKuyiuZCWcH_XV7Hdo

Some quick "don't"s:

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • Don't use map if you're not using its return value. (There's sadly someone out there teaching map [spec / MDN] as though it were forEach — but as I write on my blog, that's not what it's for. If you aren't using the array it creates, don't use map.)
  • Don't use forEach if the callback does asynchronous work and you want the forEach to wait until that work is done (because it won't).

哥,我好想在 Array 的高階函數前面 await 喔!該怎麼做呢? https://realdennis.medium.com/%E5%93%A5-%E6%88%91%E5%A5%BD%E6%83%B3%E5%9C%A8-array-%E7%9A%84%E9%AB%98%E9%9A%8E%E5%87%BD%E6%95%B8%E5%89%8D%E9%9D%A2-await%E5%96%94-%E8%A9%B2%E6%80%8E%E9%BA%BC%E5%81%9A%E5%91%A2-2d75e07e3adb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment