关于承诺{<pending>}

时间:2019-08-16 05:29:56

标签: javascript node.js promise

在文件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运行上述程序时,得到以下输出:

  

找到文件
  输出:承诺{}
  访问网址:http://example.com/pqr.png

我的问题是-为什么我得到:Output: Promise { <pending> }?我遵循的示例是here,所以我希望在我分别调用readFile()reject()时在resolve()中兑现承诺。我认为我在.then()中使用getImage.js 消费了promise。为什么程序说promise仍在等待中?我想念什么?

谢谢!

0 个答案:

没有答案
相关问题