javascript - 关于承诺{}
问题描述
在文件readFile.js
中,函数readFile()
定义如下:
function readFile(path) {
return new Promise(function(resolve, reject){
if(!fs.existsSync(path)) {
console.log('Will throw error now!');
reject("memes.json file does not exist");
}
else {
//File exists
console.log('File found');
var data = fs.readFileSync(path, 'utf8');
resolve(data);
}
})
}
module.exports.readFile = readFile;
在文件getImage.js
中,targetImage
定义如下:
var targetImage = data.readFile(path)
.then(function(value) {
var jsonData = JSON.parse(value);
for(let i=0; i<jsonData.length; i++) {
if(jsonData[i].title == memeImage) {
console.log('Visit URL: ', jsonData[i].image);
return jsonData[i].image;
}
}
})
.catch(function(err) {
console.log('Encountered some error during reading file');
return 'Errored out :(';
});
module.exports = targetImage;
最后,文件modifyImage.js
简单地具有:
console.log('Output: ', targetImageValue);
当我运行上述程序时node ./lib/modifyImage.js -n Determined
,我得到以下输出:
找到文件
输出:Promise { }
访问 URL: http ://example.com/pqr.png
我的问题是 - 为什么我会得到:Output: Promise { <pending> }
?我在这里readFile()
按照示例进行操作,因此我希望在我调用reject()
and时能够兑现承诺resolve()
。我想我正在使用in消耗承诺。为什么程序说承诺仍在等待中?我错过了什么?.then()
getImage.js
谢谢!
解决方案
推荐阅读
- r - 如何生成一个 svytableone,它显示按 z 分组的 x 的数量?
- python - python将值插入MySQL-.DatabaseError:1366(HY000):字符串值不正确:'\ x92
- javascript - React Router 不会在道具上重新渲染相同的组件
- python - 脏话过滤器无法加载 Spacy 模型“en”
- python - Kivy:尝试加载远程 mp4 时,Gstreamer 插件不起作用
- cookies - cakePHP中间件中如何设置默认cookie参数
- svg - 我如何创建一个结合了 feTurbulence 和 feGaussianBlur 的 svg 过滤器
- c# - VS Code 中用于 Unity 的 Visual Studio 工具?
- git - 尝试使用 https 将存储库克隆到 NetBeans 时凭据不正确
- gcc - 在 64 位 (x86-64) 机器上构建 32 位 (x86) gcc-10.2.0 时出错