Javascriptcallback函数 – Node.js
我有两个function,
1) download(uri, filename, callback)
– >将图像下载到特定位置
2) twitterPost(filename)
– >推文的形象
我需要这样做asynchronous – 所以我打电话twitterPost
图像完成下载后,但是我每次都收到此错误:
throw new Error('File path does not exist: ' + media); ^ Error: File path does not exist: Imgs/18478-wrt1114.jpg
现在我明白了,这是因为图像没有下载而出现,但是在closurespipe道之后看到callback函数是没有意义的。 这是我的两个函数的代码:
function download(uri, filename, callback) { request.head(uri, function(err, res, body) { request(uri).pipe(fs.createWriteStream(filename)).on('end', callback); }); };
和
function twitterPost(filename) { var twitterRestClient = new Twitter.RestClient( // API KEYS AND STUFF HERE ); twitterRestClient.statusesUpdateWithMedia( { 'status': 'Test Tweet', 'media[]': filename }, function(error, result) { if (error) { console.log('Error: ' + error.message) } if (result) { console.log(result.text) } }); }
这是我的函数调用:
download(image, filename,twitterPost(filename));
我使用callback不正确,还是有一些其他问题,我不知道导致这个问题
谢谢你的帮助!
我使用callback不正确
是的,你实际上没有传递callback函数 。 你传递的结果立即调用twitterPost(filename)
– 这发生在download
被调用之前,所以没有这样的文件呢。
围绕这个调用使用一个函数expression式来获得由download
调用的函数:
download(image, filename, function(endEvent) { twitterPost(filename); });
我认为你的问题是由于你传递参数到你的函数的方式。
download(image, filename,twitterPost(filename));
检查twitterPost(filename)
,你的文件名是预期的。 我很确定它不会。 这是因为你的twitterPost函数没有被这个参数调用。 它被称为:
request(uri).pipe(fs.createWriteStream(filename)).on('end', callback);
那就是没有参数。 我会做 :
request(uri).pipe(fs.createWriteStream(filename)).on('end', function(){ callback(filename); });