首页 > 解决方案 > 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

标签: javascript

解决方案


您的循环应该在异步函数中,并等待调用的结果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()


推荐阅读