【发布时间】:2019-06-22 08:37:33
【问题描述】:
无法在 readline.on 函数下使用 await/async 我不知道为什么它不等到结果返回?在等待函数下也使用了promise,但是当我返回promise时也没有用。哪位精通node js,Es6的高手可以帮帮我,这是我对所有开发者的谦卑要求。谁能帮我解决这个问题,提前谢谢。
var readline = require('readline');
fs = require('fs');
redis = require('redis');
var redisClient = redis.createClient();
var filePath = './sample-data/whoodle_index_file_0.psv';
async function getSampleData() {
let rl = readline.createInterface({
input: fs.createReadStream(filePath),
crlfDelay: Infinity
});
rl.on('line', async (line) => {
let obj = {};
let data = line.split('|');
obj['name'] = data[0];
console.log('first line of execution process');
let result = await getDataFromRedisUsingKey(obj['name']);
console.log('result' + result);
console.log('secound line of execution process');
console.log('want to use this results in to some other functions');
let obj2 = {};
obj2['name'] = data[3];
console.log('third line of execution process');
let result2 = await getDataFromRedisUsingKey(obj2['name']);
console.log('result' + result);
console.log('fourth line of execution process');
console.log('want to use this results in to some other functions');
});
}
getSampleData();
async function getDataFromRedisUsingKey(name) {
return new Promise(function (resolve, reject) {
redisClient.get(name, function (err, result) {
console.log("result----------------------" + result);
if (err) {
reject();
} else {
resolve(result);
}
});
});
}
Showing result like this on console
first line of execution process
first line of execution process
result----------------------null
result----------------------null
resultnull
secound line of execution process
want to use this results in to some other functions
third line of execution process
resultnull
secound line of execution process
want to use this results in to some other functions
third line of execution process
result----------------------null
result----------------------null
result2null
fourth line of execution process
want to use this results in to some other functions
result2null
fourth line of execution process
want to use this results in to some other functions
But im expecting like this
first line of execution process
result----------------------null
resultnull
secound line of execution process
want to use this results in to some other functions
third line of execution process
result----------------------null
result2null
fourth line of execution process
want to use this results in to some other functions
first line of execution process
result----------------------null
resultnull
secound line of execution process
want to use this results in to some other functions
third line of execution process
result----------------------null
result2null
fourth line of execution process
want to use this results in to some other functions
【问题讨论】:
-
你忘了
awaitPromise。您还应该reject处理错误,而不是resolve -
如果我创建一个具有某个名称的函数并将其粘贴新的承诺代码并使用 await 调用该函数也同样没有用,我的意思是 await 函数没有首先执行
-
如果您需要调试帮助,请发布该代码。
-
刚刚更新问题,请再次查看
-
你应该“回报”承诺
标签: javascript node.js ecmascript-6 es6-promise