首页 > 解决方案 > 关于承诺{}

问题描述

在文件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

谢谢!

标签: javascriptnode.jspromise

解决方案


推荐阅读