Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中同步打印承诺?(How to print a promise synchronously in JavaScript?)

I have the following function returns a Promise, which resolves to a random word string .(我有以下函数返回一个Promise,它解析为一个随机单词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 .(我有一个for循环,从1到10。每次迭代, 如果数字是3的倍数,我需要打印“ Divided”,否则打印一个随机单词 。) The problem is all the random numbers are printing at the end of the for loop, not in the order .(问题是所有随机数都在for循环的末尾而不是按顺序打印 。) I tried with " await " but it says "await is only valid in async function".(我尝试使用“ await ”,但是它说“ await仅在异步函数中有效”。) How can I do this task?(我该怎么做?) (I need to keep getRandomWord function as it is)((我需要保持getRandomWord函数原样)) 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(3:分开) 6: divided(6:分开) 9: divided(9:分开) 11: chart(11:图表) 11: definition(11:定义) 11: suggest(11:建议) 11: stone(11:石头) 11: bet(11:打赌) 11: circus(11:马戏团) 11: classroom(11:教室)   ask by David Johns translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your loop should be within an async function, and await the result of the call to getRandomWord(您的循环应在异步函数内,并等待对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); } } } Live example below.(下面的直播示例。) 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...