我有以下代码。我仅在打印前一个console.log
之后尝试story
下一个story
,但是它正在打印Promise { <pending> }
。我是async
和await
的新手。我在这里想念什么?
服务器
const express = require('express')
const async = require("async");
const app = express()
const port = 3000
const time = require('./timeoutFun.js')
const array = [
{author: 'Bill',
story: ['This', 'is', 'the', 'first', 'story']},
{author: 'Frank',
story: ['Here', 'goes', 'another']},
{author: 'Tom',
story: ['Fine', 'another', 'things', 'I', 'wrote']},
{author: 'Sam',
story: ['No', 'more', 'writings', 'please']}
]
array.forEach(element => {
console.log(time.promiseTime(element))
});
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
timeoutFun.js
const time = {
promiseTime: async function (obj) {
const randomNum = Math.floor(Math.random() * 5)
return await new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(obj.story.toString() + " " + randomNum);
}, randomNum * 1000);
})
}
}
module.exports = time;
答案 0 :(得分:2)
不要一起使用async function
和return promise
。异步函数自动返回一个Promise只是返回结束值,但是在这种情况下,因为您使用的是setTimeout,那么您将需要返回承诺,因此只需使用返回承诺即可。
forEach不等待承诺完成,因此它将全部启动,然后跳至下一行,因此请使用for(let e of a){}
您必须await
这样的承诺,例如let result = await time.promiseTime(ele)
才能真正获得价值,否则,您只会得到承诺(或者使用.then(result=>{...})
)
const time = {
promiseTime: function (obj) {
const randomNum = Math.floor(Math.random() * 5)
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(obj.story.toString() + " " + randomNum);
}, randomNum * 1000);
})
}
};
const array = [
{author: 'Bill',
story: ['This', 'is', 'the', 'first', 'story']},
{author: 'Frank',
story: ['Here', 'goes', 'another']},
{author: 'Tom',
story: ['Fine', 'another', 'things', 'I', 'wrote']},
{author: 'Sam',
story: ['No', 'more', 'writings', 'please']}
];
async function main(){
for(let ele of array){
let result = await time.promiseTime(ele);
console.log(result);
};
}
main();