简体   繁体   English

Node.js 处理承诺的最佳方式

[英]Node.js best way to handle promises

So I have code that looks like this in my controller.所以我的 controller 中有这样的代码。

const Users = require("../models/users");    

class UserController() {
    getUserById(req, res) {
        const id = req.params.id;
        const users = new Users();
        const userData = users.getUserById(uid).then(function(result) {
            //Do other logic here that depends on db result
            return res.status(200).json({status:"success", user: result});
        });
    }
}

My question is, what's the difference between that and the following, and which is the better practice?我的问题是,这与以下有什么区别,哪个是更好的做法?

const Users = require("../models/users");    

class UserController() {
    async getUserById(req, res) {
        const id = req.params.id;
        const users = new Users();
        const userData = await users.getUserById(uid);
        return res.status(200).json({status:"success",user:userData});
    }
}

The second function call is using async-await feature of ES8, This makes our code appear as if it is synchronous and clean also, without doing .then() and callback within it.第二个 function 调用使用了 ES8 的async-await特性,这使得我们的代码看起来也是同步和干净的,无需在其中执行.then()和回调。 Both fetch() and async-await work on promise though. fetch()async-await都可以在 promise 上工作。

Aync-Await is much more readable if I can put it this way.如果我可以这样说, Aync-Await 的可读性会更高。 No call backs used here.这里没有使用回调。 It simply waits for the first API call to happen and only when the data arrives (or Promise is resolved) we fire another API call.它只是等待第一个 API 调用发生,并且只有当数据到达(或 Promise 已解决)时,我们才会触发另一个 API 调用。 For programmer itself life becomes little easy with Async-Await syntax.对于程序员本身来说,使用 Async-Await 语法变得不那么容易了。

For Error handling you will need try{} catch{} block in Aync-await but in case of fetch() , .catch() block handles API Errors for us.对于错误处理,您将需要Aync-await中的try{} catch{}块,但在fetch()的情况下, .catch()块会为我们处理 API 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM