2016-12-15 73 views
0

圍繞異步環繞我的頭。這會在異步環境中工作嗎?會在nodejs中異步工作嗎?

發佈並檢查一個參數,並在每次發佈時返回true或false,還是會阻止?

用戶json是mongodb請求的替代者。

'use strict';

const serverport = process.env.PORT; 

let users = [{ 
"id": 1, 
"name": "Leanne Graham", 
"username": "Bret", 
"email": "[email protected]", 
"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); 
}); 
+0

當然這會奏效。什麼把你扔掉了?函數'checkName'不是沒有回調的事實?如果是這樣,那並不重要,你可以在任何地方都有你的功能。另外,如果我可能會建議好的做法:對於任何不會改變的變量(如'checkName'和'express'),使用'const'而不是'let'。另外考慮簡化你的返回值:'return va === obj' –

回答

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; 
} 

確定這也不起作用,因爲「用戶」變量是一個awaitable或承諾取決於在你使用的庫上。

我們該如何解決它?

awaitable -

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 
}); 

我希望澄清了如何因爲沒有處理在您選擇上下文中的異步的情況下,任何方式你上面給出的代碼應該只是罰款涉及的異步操作。