gpt4 book ai didi

node.js - 在 Node 中使用 async await 排队作业

转载 作者:搜寻专家 更新时间:2023-11-01 00:49:49 25 4
gpt4 key购买 nike

我有以下代码。我试图 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;

最佳答案

  1. 不要同时使用async functionreturn promise.. async functions return a promise automatically return the end value, but in this case since you如果正在使用 setTimeout,那么您需要返回一个 promise ,因此只需使用 return promise。

  2. forEach 不会等待 promise 完成,所以它会启动所有 promise 然后跳到下一行,因此请改用 for(let e of a){}

  3. 您必须 await promise ,例如 let result = await time.promiseTime(ele) 才能实际获取值,否则您只会获取 promise (或者使用 .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();

关于node.js - 在 Node 中使用 async await 排队作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com