Ran*_*Joe 3 javascript node.js promise async-await ecmascript-2017
我正在使用Node版本7.6.0来尝试本机异步和等待功能.
我试图找出为什么我的异步调用只是挂起从来没有真正解决.
NLP模块:
const rest = require('unirest')
const Redis = require('ioredis')
const redis = new Redis()
const Promise = require('bluebird')
const nlp = {}
nlp.queryCache = function(text) {
return new Promise(function(resolve, reject) {
redis.get(text, (err, result) => {
if (err) {
console.log("Error querying Redis: ", err)
reject(new Error("Error querying Redis: ", err))
} else {
if (result) {
let cache = JSON.parse(result)
console.log("Found cache in Redis: ", cache)
resolve(cache)
} else {
resolve(null)
}
}
})
})
}
nlp.queryService = function(text) {
console.log("Querying NLP Service...")
return new Promise(function(resolve, reject) {
rest.get('http://localhost:9119?q=' + text)
.end((response) => {
redis.set(text, JSON.stringify(text))
resolve(response.body)
})
})
}
nlp.query = async function(text) {
try {
console.log("LET'S TRY REDIS FIRST")
let cache = await nlp.queryCache(text)
if (cache) {
return cache
} else {
let result = await nlp.queryService(text)
console.log("Done Querying NLP service: ", result)
return result
}
} catch (e) {
console.log("Problem querying: ", e)
}
}
module.exports = nlp
Run Code Online (Sandbox Code Playgroud)
模块消费者:
const modeMenu = require('../ui/service_mode')
const nlp = require('../nlp')
const sess = require('../session')
const onGreetings = async function(req, res, next) {
let state = sess.getState(req.from.id)
if (state === 'GREET') {
let log = {
middleware: "onGreetings"
}
console.log(log)
let result = await nlp.query(req.text)
console.log("XXXXXXXX: ", result)
res.send({reply_id: req.from.id, message: msg})
} else {
console.log("This query is not not normal text from user, calling next()")
next()
}
};
module.exports = onGreetings;
Run Code Online (Sandbox Code Playgroud)
我无法获取代码以继续执行以下行:
console.log("XXXXXXXX: ", result)
Run Code Online (Sandbox Code Playgroud)
我可以看到NLP模块中的查询成功
最可能的原因是你没有捕获的Promise错误.我觉得有必要避免try- catch除了顶级调用方法之外的所有方法,并且如果一个方法可以await-ed它几乎总是应该.
在你的情况下,我认为问题出在这里:
nlp.queryService = function(text) {
console.log("Querying NLP Service...")
return new Promise(function(resolve, reject) {
rest.get('http://localhost:9119?q=' + text)
.end((response) => {
redis.set(text, JSON.stringify(text)) // this line is fire and forget
resolve(response.body)
})
})
}
Run Code Online (Sandbox Code Playgroud)
特别是这一行:redis.set(text, JSON.stringify(text))- 该行正在调用一个函数,没有任何错误.
修复是将所有Redis方法包装在promises中,然后始终将await它们包装起来:
nlp.setCache = function(key, value) {
return new Promise(function(resolve, reject) {
redis.set(key, value, (err, result) => {
if (err) {
reject(new Error("Error saving to Redis: ", err));
} else {
resolve(result);
}
});
})
}
nlp.queryService = async function(text) {
console.log("Querying NLP Service...")
const p = new Promise(function(resolve, reject) {
rest.get('http://localhost:9119?q=' + text)
.end((response) => { resolve(response.body) });
// This is missing error handling - it should reject(new Error...
// for any connection errors or any non-20x response status
});
const result = await p;
// Now any issue saving to Redis will be passed to any try-catch
await nlp.setCache(text, result);
return;
}
Run Code Online (Sandbox Code Playgroud)
作为一般规则,我发现最佳做法是:
Promise为您rest和redis回调设置包装函数.reject有new Error出问题的时候.如果a Promise没有resolve,reject那么你的代码就会停止.awaittry- catch在顶部 - 只要每个Promise都是 - await任何一个错误抛出的任何错误将最终在顶层catch大多数问题将是:
Promise可能失败resolve或reject.async function或Promise没有await.| 归档时间: |
|
| 查看次数: |
3102 次 |
| 最近记录: |