这会在nodejs中异步工作吗?

时间:2016-12-15 14:35:18

标签: node.js

把我的脑袋缠绕在异步上。这会在异步环境中工作吗?

每次发布​​和检查一个参数并在帖子上返回true或false,还是会阻止它?

用户json是mongodb请求的代表。

'use strict';

const serverport = process.env.PORT;

let users = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
    }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
}
}]

let checkName = (obj) => {
    let va = users[0].email;
    return (va === obj) ? true : false;
}

let express = require("express"),
app = express();

app.post('/reg', (req, res, next) => {
    if (checkName(req.param.email) == true) {
    //render email already taken    
    } else {
    //render email is not taken and complete registration
    }
});

app.listen(serverport, (req, res, next) => {
    console.log('server is listening on port: ' + serverport);
});

1 个答案:

答案 0 :(得分:0)

这似乎完全没问题, 让我们看一个可能不正常的例子:

const serverport = process.env.PORT;

let users = mongoDb.getUsersAsync();

let checkName = (obj) => {
    let va = users[0].email; 
    // this point does not wait for the async request to finish, 
    // therefore will not work ! 
    return (va === obj) ? true : false;
}

好的,这个不会起作用,因为"用户"变量是等待的,或者取决于你正在使用的库。

我们该如何解决?

等待 -

const serverport = process.env.PORT;

let users = await mongoDb.getUsersAsync();

let checkName = (obj) => {
    let va = users[0].email; 
    // this point does not wait for the async request to finish, 
    // therefore will not work ! 
    return (va === obj) ? true : false;
}

现在"用户"变量等待,直到mongodb异步请求完成并获取数据。

如果它是我们以不同方式处理它的承诺 -

const serverport = process.env.PORT;

let usersPromise = mongoDb.getUsersAsync((users) => { 
    let checkName = (obj) => {
        let va = users[0].email; 
        return (va === obj) ? true : false;
    }

    // ... the rest of youre code  
});

我希望在你的上下文中清除如何处理异步情况,上面提到的代码应该可以正常工作,因为不涉及异步操作。