NodeJS 使用async await和setImmediate

1rhkuytd  于 2023-05-22  发布在  Node.js
关注(0)|答案(4)|浏览(137)

我想知道如何使用async await和setImmediate来正确处理错误。我写了以下代码。但我不确定它是否遵循了最佳做法。
我的快递APP里有一条路线

router.get('/parseinvoice', async (req, res, next) => {
    try {
        const parsedInvoiceResponse = await userhelper.getParseInVoiceList();
        res.json({parsedInvoiceResponse})
    } catch (error) {
        res.json({});
    }
});

userhelper类代码

var userhelper = {};
const fs = require('fs'),
      path = require('path'),    
      filePath = path.join(__dirname, './input_user_story_12.txt');

const { promisify } = require('util')
const readFile = promisify(fs.readFile);


userhelper.getParseInVoiceList = async function() {
    return new Promise( async (resolve, reject) => {
        try {
            setImmediate(async function() {
                try {
                    const contents = await readFile(filePath, 'UTF-8');
                    resolve(contents);
                } catch (error) {
                    reject(error);
                }
            });
        } catch (error) {
           reject(error); 
        }
    });
}

module.exports = userhelper;

虽然我得到了回应。我不确定setImmediate部分,是否需要多次 try catch。有没有什么简洁的方法来写下面的代码?.

nhhxz33t

nhhxz33t1#

try {
    setImmediate(async ()=>{
        var res = await readFile(filePath, 'UTF-8');
    })
} catch(err) {
}
await setImmediate(()=>{
       var res = await readFile(filePath, 'UTF-8');
}).catch(){}
try {
    await setImmediate(()=>{
       await readFile(filePath, 'UTF-8');
    }).catch(){}
} catch() {
}

1.应将结果返回到res中

const res = await setImmediate(()=>{
     return readFile(filePath, 'UTF-8');
})
w6mmgewl

w6mmgewl2#

你为什么不吸毒?

userhelper.getParseInVoiceList = async function() {
    return await readFile(filePath, 'UTF-8');
}
6tqwzwtp

6tqwzwtp3#

扩展@Dan D.的答案,您可以在调用异步promised readFile之前await异步setImmediate的分辨率,但我不确定为什么您需要在没有更多上下文的情况下这样做。

userhelper.getParseInVoiceList = async function() {
    await new Promise((resolve) => setImmediate(() => resolve()));
    return await readFile(filePath, 'UTF-8');
}
64jmpszr

64jmpszr4#

从Node 15开始,您可以使用timersPromises.setImmediate

​import { readFile } from "fs/promises";
import { setImmediate as sleepImmediate } from "timers/promises";

userhelper.getParseInVoiceList = async function() {
  await sleepImmediate();
  return await readFile(filePath, 'UTF-8');
}

相关问题