javascript - How to print a promise synchronously in JavaScript?
问题描述
I have the following function returns a Promise, which resolves to a random word string. And I have a for loop go from 1 to 10. Each iteration, if the number is multiple of 3, I need to print "Divided" otherwise print a random word. The problem is all the random numbers are printing at the end of the for loop, not in the order. I tried with "await
" but it says "await is only valid in async function". How can I do this task? (I need to keep getRandomWord function as it is)
const randomWords = require('random-words');
function getRandomWord() {
return new Promise((resolve) => {
setTimeout(
() => resolve(randomWords())
);
});
}
for (i=1; i<=10; i++) {
if (i%3 === 0) {
console.log(i + ": " + "divided" );
}
else {
getRandomWord().then(result => {
console.log(i + ": " + result);
});
}
}
Output
3: divided
6: divided
9: divided
11: chart
11: definition
11: suggest
11: stone
11: bet
11: circus
11: classroom
解决方案
您的循环应该在异步函数中,并等待调用的结果getRandomWord
async function doWork()
{
for (i=1; i<=10; i++) {
if (i%3 === 0) {
console.log(i + ": " + "divided" );
}
else {
var result = await getRandomWord()
console.log(i + ": " + result);
}
}
}
下面的实时示例。
function getRandomWord() {
return new Promise((resolve) => {
setTimeout(
() => resolve("Hello, World")
);
});
}
async function doWork()
{
for (i=1; i<=10; i++) {
if (i%3 === 0) {
console.log(i + ": " + "divided" );
}
else {
var result = await getRandomWord()
console.log(i + ": " + result);
}
}
}
doWork()
推荐阅读
- reactjs - 如何在 React 中将数据从一个组件传递到另一个组件
- excel - 如何使用单元格内的十六进制颜色值突出显示单元格(但适用于最新版本的 Excel)
- sql - 将日期格式数字转换为日期并在 SQL 中取差
- digital-ocean - 将私钥添加到 FileZilla 时出现“无法从 fzputtygen 获得回复”错误
- c# - 使用 Angular 的 C# Lambda 表达式生成器
- stata - Stata,根据与其他观察值的相对位置制作变量
- ruby-on-rails - form_with 不会在 rails 6 中发布所有数据
- apache - HTTPS 连接列出我的目录而不是执行我的应用程序
- javascript - 将 DataTable 表添加到现有表的数组中
- .htaccess - 如何使用 htaccess 删除 index.php