lau*_*kok 4 mongoose node.js promise express ecmascript-2017
有一个件事令我望而却步与承诺是,它是很难把握resolve和reject。包裹的需要Promise也是丑陋的。除非您经常使用它,否则我会逐渐忘记如何使用它们。此外,带有的代码Promise仍然混乱且难以阅读。因此,我根本不喜欢使用它-因为它与回调地狱没有太大区别。因此,我认为使用ES7 await可以避免使用Promise并使我对JavaScript有更多的信心,但是事实并非如此。例如:
const getOne = async () => {
return Weather.findOne(options, function(err, weather) {
//
});
}
const getWeather = async () => {
const exist = await getOne();
if (exist == null) {
return new Promise(function(resolve, reject) {
// Use request library.
request(pullUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Resolve with the data.
resolve(body);
} else {
// Reject with the error.
reject(error);
}
});
});
}
}
const insertWeather = async () => {
try {
const data = await getWeather();
} catch (err) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
}
}
insertWeather();
Run Code Online (Sandbox Code Playgroud)
request(pullUrl, function (error, response, body) {}是来自请求包的针对nodejs 的AJAX调用。
我不得不换用它Promise-但与它前面await。理想情况下,这就是我的想象:
return await request(pullUrl, function (error, response, body) {...}
Run Code Online (Sandbox Code Playgroud)
但是,如果这样做,我将获得返回的请求对象,而不是从包返回的数据request -在这一行:
const data = await getWeather();
有什么想法或解决方案可以避免Promise在上述情况下使用?
您会发现bluebird和node.js随带了promisify,可让您根据需要使用Node回调。另外,您可以考虑使用功能性反应式方法,并使用RxJS之类的库来处理Promise,节点回调和流中的其他数据类型。
const promisify = require('utils').promisify // alternatively use bluebird
const request = require('request-promise');
const weatherFn = promisify(Weather.findOne);
const weatherOptions = {};
async function getWeatherIfDoesNotExist() {
try {
const records = await weatherFn(weatherOptions);
if (records === null) {
return await request('/pullUrl');
}
} catch(err) {
throw new Error('Could not get weather');
}
}
async function weatherController(req, res) {
try {
const data = await getWeatherIfDoesNotExist();
} catch (err) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
}
}
function altWeatherController(req, res) {
return getWeatherIfDoesNotExist()
.then((data) => { // do something })
.catch((err) => {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1682 次 |
| 最近记录: |