gpt4 book ai didi

javascript - 如何在 `app.get` 回调中使用异步响应值

转载 作者:太空宇宙 更新时间:2023-11-04 00:32:57 24 4
gpt4 key购买 nike

我想使用 flickrapi ( https://www.npmjs.com/package/flickrapi ) 包。我需要授权:

Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//I need this flickr variable
});

我想在我的快速代码中使用这个 flickr 变量

app.get('/', function (req, res) {
//do something with flickr
});

我该怎么做?

最佳答案

模块化方法:

将您的 flickr 连接代码分开:

flickr-public.js

var Flickr = require("flickrapi"),
flickrOptions = {
api_key: "API key that you get from Flickr",
secret: "API key secret that you get from Flickr"
};

module.exports = (function(){
Flickr.tokenOnly(flickrOptions, function(error, flickr) {
//handle error here
console.log('Flickr Object Obtained');
return flickr;
});
})();

Note: Better instantiate the flickr object in your app.js file. So that the object gets created immediately when server starts. As this flickr object is for public API only and does not need authentication again and again.

您只需在 app.js 文件中引用 flickr 对象即可实例化该对象:

require('./flickr-public');

现在只需通过请求即可在任何地方访问 flickr 对象。

routes.js

const flickr = require('../path-to/flickr-public');

app.get('/', function (req, res) {
//use flickr object to perform actions.
});

说明:

来自node.js documentation :

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file. Multiple calls to require('foo') may not cause the module code to be executed multiple times.

关于javascript - 如何在 `app.get` 回调中使用异步响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40262522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com